问题与发送POST / GET以获取Python中的Web内容

时间:2012-10-15 12:52:57

标签: python post cookies get

  

可能重复:
  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的某些cookiejar / cookielib因为我应该解决上面提到的这个错误但是我不知道如何重新编码我的代码: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。对不起我的英语,但我不是本地人。

1 个答案:

答案 0 :(得分:0)

@Piotr Dobrogost感谢这个链接,它解决了这个问题。

使用data=b"string"代替data="string"

解决了TypeError问题

由于移植到python3,我仍然遇到了一些问题,但问题是要关闭。