且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python网页中获取当前URL?

更新时间:2023-02-21 15:25:38

如果您没有任何库来为您执行此操作,您可以从通过浏览器发送到您的脚本的 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.