如何在python网页中获取当前URL? [英] How to get current URL in python web page?

查看:108
本文介绍了如何在python网页中获取当前URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 的菜鸟.刚刚安装了它,并花了 2 个小时在谷歌上搜索如何获取发送到 Python 脚本的 URL 中的简单参数

I am a noob in Python. Just installed it, and spent 2 hours googleing how to get to a simple parameter sent in the URL to a Python script

找到这个

非常有帮助,除了我不能为世界上的任何东西弄清楚如何替换

Very helpful, except I cannot for anything in the world to figure out how to replace

import urlparse
url = 'http://foo.appspot.com/abc?def=ghi'
parsed = urlparse.urlparse(url)
print urlparse.parse_qs(parsed.query)['def']

用什么替换 url = 'string' 以使其工作?我只想访问 http://site.com/test/test.py?param=abc 并看到 abc 打印出来.

With what do I replace url = 'string' to make it work? I just want to access http://site.com/test/test.py?param=abc and see abc printed.

Alex 回答后的最终代码:

Final code after Alex's answer:

url = os.environ["REQUEST_URI"] 
parsed = urlparse.urlparse(url) 
print urlparse.parse_qs(parsed.query)['param']

推荐答案

如果您没有任何库来为您执行此操作,您可以从通过浏览器发送到您的脚本的 HTTP 请求构建您当前的 URL.

If you don't have any libraries to do this for you, you can construct your current URL from the HTTP request that gets sent to your script via the browser.

您感兴趣的标头是 Host 以及 HTTP 方法之后的任何内容(在您的情况下可能是 GET).这里有更多解释(第一个链接似乎没问题,你可以自由地谷歌更多:).

The headers that interest you are Host and whatever's after the HTTP method (probably GET, in your case). Here are some more explanations (first link that seemed ok, you're free to Google some more :).

这个答案向您展示了如何在您的 CGI 脚本中获取标题:

This answer shows you how to get the headers in your CGI script:

如果您以 CGI 运行,则无法直接读取 HTTP 标头,但是网络服务器将大部分信息放入环境中你的变量.你可以从 os.environ[] 中选择它.

If you are running as a CGI, you can't read the HTTP header directly, but the web server put much of that information into environment variables for you. You can just pick it out of os.environ[].

如果您将此作为练习,那很好,因为您将了解幕后的情况.如果您正在构建任何可重用的东西,我建议您使用库或框架,这样您就不会在每次需要时都重新发明轮子.

If you're doing this as an exercise, then it's fine because you'll get to understand what's behind the scenes. If you're building anything reusable, I recommend you use libraries or a framework so you don't reinvent the wheel every time you need something.

这篇关于如何在python网页中获取当前URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆