加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何使用Python urlopen设置cookie?

发布时间:2020-12-20 11:23:19 所属栏目:Python 来源:网络整理
导读:我试图使用 Python urlopen获取一个html站点. 我收到此错误: HTTPError: HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop 代码: from urllib2 import Requestrequest = Request(url)response = urlopen(r
我试图使用 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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读