gpt4 book ai didi

python - 使用 Mechanize (Python) 获取重定向日志

转载 作者:行者123 更新时间:2023-12-04 05:54:19 26 4
gpt4 key购买 nike

我想使用 Python 编写的 Mechanize 获取 url 重定向日志。例如,www.google.com --> www.google.co.in。之前在 SO 中已经问过确切的问题,但它是针对 Ruby 的

How to get redirect log in Mechanize?

答案解释说,要做到这一点,可以在 Ruby 中执行以下操作 -

for m.redirection_limit in 0..99
begin
m.get(url)
break
rescue WWW::Mechanize::RedirectLimitReachedError
# code here could get control at
# intermediate redirection levels
end
end

我想用 Python 做同样的事情。有什么帮助吗? Python for Mechanize 中 get(url) 的替代方法是什么?

最佳答案

您可以覆盖 HTTPRedirectHandler.redirect_request()保存重定向历史记录的方法:

import urllib2

class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
newreq = urllib2.HTTPRedirectHandler.redirect_request(self,
req, fp, code, msg, headers, newurl)
if newreq is not None:
self.redirections.append(newreq.get_full_url())
return newreq

url = 'http://google.com'

h = HTTPRedirectHandler()
h.max_redirections = 100
h.redirections = [url]
opener = urllib2.build_opener(h)
response = opener.open(url)
print h.redirections
# -> ['http://google.com', 'http://www.google.com/', 'http://google.com.ua/']

它应该比提供的 WWW::Mechanize 快得多代码片段,因为 urllib2每个网址只访问一次。
mechanize提供 urllib2 的超集功能,即,如果您使用 mechanize然后只需替换每次出现的 urllib2以上与 mechanize它会起作用。

关于python - 使用 Mechanize (Python) 获取重定向日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9702492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com