如何使用Python urlopen设置cookie?

我试图使用
Python urlopen获取一个html站点.

我收到此错误:

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

代码:

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

我知道服务器重定向到另一个URL并且它正在寻找cookie.
如何设置它正在寻找的cookie,以便我可以阅读html?

最佳答案 以下是
Python documentation的示例,根据您的代码调整:

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