How do I set cookies using Python urlopen?

好久不见. 提交于 2019-12-20 17:28:07

问题


I am trying to fetch an html site using Python urlopen.
I am getting this error:

HTTPError: HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop

The code:

from urllib2 import Request
request = Request(url)
response = urlopen(request)

I understand that the server redirects to another URL and that it is looking for a cookie.
How do I set the cookie it is looking for so I can read the html?


回答1:


Here's an example from Python documentation, adjusted to your code:

import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
request = urllib2.Request(url)
response = opener.open(request)


来源:https://stackoverflow.com/questions/9113652/how-do-i-set-cookies-using-python-urlopen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!