如何使用Python urlopen设置cookie? [英] How do I set cookies using Python urlopen?

查看:1100
本文介绍了如何使用Python urlopen设置cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Python urlopen获取一个html网站。

我收到此错误:

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


HTTP错误:HTTP错误302:HTTP服务器返回会导致无限循环的重定向错误

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?

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?

推荐答案

这里是 Python文档,调整为您的代码:

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)

这篇关于如何使用Python urlopen设置cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆