使用Mechanize(Python)获取重定向日志
我想使用Python编写的Mechanize获取url重定向日志。例如,www.google.com-->www.google.co.in。在SO中,确实有人问过这个问题,但这是针对Ruby的 答案解释说,要做到这一点,可以在Ruby中执行以下操作-使用Mechanize(Python)获取重定向日志,python,mechanize,mechanize-python,Python,Mechanize,Mechanize Python,我想使用Python编写的Mechanize获取url重定向日志。例如,www.google.com-->www.google.co.in。在SO中,确实有人问过这个问题,但这是针对Ruby的 答案解释说,要做到这一点,可以在Ruby中执行以下操作- for m.redirection_limit in 0..99 begin m.get(url) break rescue WWW::Mechanize::RedirectLimitReachedError
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中,Mechanize的get(url)的替代方法是什么?我本来想给你一个“IGIFY”,但你是对的,Mechanize文档很糟糕。稍微转一转,看起来您应该看看urllib2,因为mechanize公开了整个接口。您可以覆盖
HTTPRedirectHandler.redirect\u 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
代码片段快得多,因为urlib2
只访问每个url一次
mechanize
提供了urlib2
功能的超集,也就是说,如果你使用mechanize
,那么只需将上面出现的urlib2
替换为mechanize
,它就会工作。import mechanize
import logging
import sys
logger = logging.getLogger("mechanize")
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.INFO)
browser = mechanize.Browser()
browser.set_debug_redirects(True)
r=browser.open("http://google.com")
使用urllib2没有帮助,因为我想使用mechanize模拟浏览器行为。他们明确表示,在该页面上多次查看urllib2文档。