【问题标题】:issue with cookies and sending POST/GET to get te web content in Python [duplicate]cookie 问题并发送 POST/GET 以在 Python 中获取 Web 内容 [重复]
【发布时间】:2012-10-05 10:52:09
【问题描述】:

可能重复:
How to use Python to login to a webpage and retrieve cookies for later usage?

我想从以某种不寻常方式处理 cookie 的服务下载整个网页源。我写了一个实际工作的脚本,似乎很好,但是在某些时候它返回了这样的错误:

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

我的脚本循环运行,并更改了指向我有兴趣下载内容的子页面的链接。

我得到一个 cookie,发送一个数据包,然后我可以访问 porper 链接,然后下载 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 阅读 sth ab cookiejar/cookielib coz 我应该摆脱上面提到的这个错误但是我不知道如何重新编写我的代码以供以下用户使用:http.cookiejar, urllib.request

我试过这样的:

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。对不起我的英语,但我不是本地人。

【问题讨论】:

    标签: python post cookies get


    【解决方案1】:

    @Piotr Dobrogost 感谢您的链接,它解决了问题。

    TypeError 通过使用data=b"string" 而不是data="string" 解决

    由于移植到python3,我仍然遇到一些问题,但问题将被关闭。

    【讨论】:

      猜你喜欢
      • 2015-11-08
      • 2011-06-29
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 2018-11-29
      相关资源
      最近更新 更多