重複の可能性:
Pythonを使用してWebページにログインし、後で使用するためにCookieを取得するにはどうすればよいですか?
なんらかの方法でCookieを処理するサービスからWebページのソース全体をダウンロードしたいと思います。私は実際に機能し、問題ないように見えるスクリプトを作成しましたが、ある時点でそのようなエラーが返されました。
urllib2.HTTPError: HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop.
The last 30x error message was:
Found
私のスクリプトはループで動作し、ダウンロードしたいサブページwchichコンテンツへのリンクを変更します。
クッキーを取得し、データのパッケージを送信すると、ポーパーリンクにアクセスしてHTMLをダウンロードできます。
スクリプトは次のようになります。
import urllib2
data = 'some_string'
url = "http://example/index.php"
url2 = "http://example/source"
req1 = urllib2.Request(url)
response = urllib2.urlopen(req1)
cookie = response.info().getheader('Set-Cookie')
## Use the cookie is subsequent requests
req2 = urllib2.Request(url, data)
req2.add_header('cookie', cookie)
response = urllib2.urlopen(req2)
## reuse again
req3 = urllib2.Request(url2)
req3.add_header('cookie', cookie)
response = urllib2.urlopen(req3)
html = response.read()
私はこのlibを使用してsthabcookiejar / cookielib cozを読んでいますが、上記のこのエラーを取り除くことになっていますが、使用するコードを再作成する方法がわかりません。http.cookiejar, urllib.request
私はこのようにsthを試しました:
import http.cookiejar, urllib.request
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener( urllib.request.HTTPCookieProcessor(cj) )
r = opener.open(url) # now cookies are stored in cj
r1 = urllib.request(url, data) #TypeError: POST data should be bytes or an iterable of bytes. It cannot be str.
r2 = opener.open(url2)
print( r2.read() )
しかし、それは私の最初のスクリプトとしては機能していません。
ps。私の英語は申し訳ありませんが、私はネイティブではありません。