我正在将 liburl2 与 CookieJar / HTTPCookieProcessor 一起使用,以尝试模拟登录页面以自动上传。
我已经看到了一些关于此的问题和答案,但没有什么能解决我的问题。当我模拟以 302 重定向结束的登录时,我丢失了我的 cookie。302 响应是服务器设置 cookie 的位置,但 urllib2 HTTPCookieProcessor 在重定向期间似乎没有保存 cookie。我尝试创建一个 HTTPRedirectHandler 类来忽略重定向,但这似乎没有奏效。我尝试全局引用 CookieJar 来处理来自 HTTPRedirectHandler 的 cookie,但是 1. 这不起作用(因为我正在处理来自重定向器的标头,而我正在使用的 CookieJar 函数 extract_cookies 需要完整的请求)和2. 这是一种丑陋的处理方式。
我可能需要一些指导,因为我对 Python 相当熟悉。我想我主要是在这里吠叫正确的树,但也许专注于错误的分支。
cj = cookielib.CookieJar()
cookieprocessor = urllib2.HTTPCookieProcessor(cj)
class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
global cj
cookie = headers.get("set-cookie")
if cookie:
# Doesn't work, but you get the idea
cj.extract_cookies(headers, req)
return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
http_error_301 = http_error_303 = http_error_307 = http_error_302
cookieprocessor = urllib2.HTTPCookieProcessor(cj)
# Oh yeah. I'm using a proxy too, to follow traffic.
proxy = urllib2.ProxyHandler({'http': '127.0.0.1:8888'})
opener = urllib2.build_opener(MyHTTPRedirectHandler, cookieprocessor, proxy)
补充:我也尝试过使用mechanize,但没有成功。这可能是一个新问题,但我会在这里提出,因为它是相同的最终目标:
这个使用 mechanize 的简单代码与 302 发射 url (http://fxfeeds.mozilla.com/firefox/headlines.xml) 一起使用时 - 请注意,不使用 set_handle_robots(False) 时会发生相同的行为。我只是想确保不是这样:
import urllib2, mechanize
browser = mechanize.Browser()
browser.set_handle_robots(False)
opener = mechanize.build_opener(*(browser.handlers))
r = opener.open("http://fxfeeds.mozilla.com/firefox/headlines.xml")
输出:
Traceback (most recent call last):
File "redirecttester.py", line 6, in <module>
r = opener.open("http://fxfeeds.mozilla.com/firefox/headlines.xml")
File "build/bdist.macosx-10.6-universal/egg/mechanize/_opener.py", line 204, in open
File "build/bdist.macosx-10.6-universal/egg/mechanize/_urllib2_fork.py", line 457, in http_response
File "build/bdist.macosx-10.6-universal/egg/mechanize/_opener.py", line 221, in error
File "build/bdist.macosx-10.6-universal/egg/mechanize/_urllib2_fork.py", line 332, in _call_chain
File "build/bdist.macosx-10.6-universal/egg/mechanize/_urllib2_fork.py", line 571, in http_error_302
File "build/bdist.macosx-10.6-universal/egg/mechanize/_opener.py", line 188, in open
File "build/bdist.macosx-10.6-universal/egg/mechanize/_mechanize.py", line 71, in http_request
AttributeError: OpenerDirector instance has no attribute '_add_referer_header'
有任何想法吗?