如何防止301代码重定向网站?
我正在尝试使用 Python 连接到网站并获取 HTTP 状态代码。作为我的另一个问题的答案建议,google.com 等网站的 HTTP 状态代码为 301 或 302(永久移动)的原因是这些服务器正在重定向。但是,我希望能够以这样的方式连接到他们,以便我从他们那里得到自然的 200(OK)。这是我当前的代码:
import httplib
conn = httplib.HTTPConnection("google.com", 80)
conn.request("GET","/")
r = conn.getresponse()
print r.status, r.reason
conn.close()
我需要更改/添加什么才能实现此目的?我听说 pycurl 库可能会帮助我,但到目前为止谷歌搜索还没有带来任何有用的结果。我是这个领域的新手,所以如果问题很琐碎,请原谅。
I am trying to connect to websites with Python and get the HTTP status codes. As answers on this other question of mine suggest, the reason that HTTP status code for websites such as google.com are 301 or 302 (permanently moved) is that these servers are redirecting. However, I would like to be able to connect to them in such a manner that I get the natural 200 (OK) from them. Here's my current code:
import httplib
conn = httplib.HTTPConnection("google.com", 80)
conn.request("GET","/")
r = conn.getresponse()
print r.status, r.reason
conn.close()
What do I need to alter/add to achieve this? I heard that pycurl
library might help me with that, but googling hasn't brought any useful results so far. I am a novice in this field, so please excuse me if the question is trivial.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您想要的是让您的代码遵循 301/302s 到返回 200 的最终 url?
如果是这样,您可以尝试使用
urllib
,或者最好仍然使用requests
,您可以使用 pip 安装它。urllib
和更可靠的requests
都应该遵循 301 和 302,并为您提供返回 200 的最终页面。有关 requests 模块的信息可以在此处找到:
。
希望这会有所帮助
I assume what you want is for your code to follow the 301/302s to the end url which returns a 200?
If so you could try using
urllib
, or better still userequests
which you can install with pip.Both
urllib
and more reliablyrequests
should follow 301's and 302's and give you the final page that returns a 200.Info on the requests module can be found here:
http://pypi.python.org/pypi/requests/
Hope this helps.