アップロードを自動化するためにページへのログインをシミュレートしようとして、CookieJar / HTTPCookieProcessor で liburl2 を使用しています。
これについていくつかの質問と回答を見てきましたが、私の問題を解決するものは何もありません。302 リダイレクトで終了するログインをシミュレートすると、Cookie が失われます。302 応答は、サーバーによって Cookie が設定される場所ですが、urllib2 HTTPCookieProcessor はリダイレクト中に Cookie を保存していないようです。リダイレクトを無視する HTTPRedirectHandler クラスを作成しようとしましたが、うまくいかなかったようです。HTTPRedirectHandler からの Cookie を処理するために CookieJar をグローバルに参照しようとしましたが、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'
何か案は?