帮助将代码从httplib2转换为urllib2
我想做什么呢?
我想访问一个网站,获取网站的cookie,然后带着这个cookie去访问下一个页面。这个过程本来是可以正常工作的,但在某个网站上,使用httplib2的时候遇到了太多问题,特别是关于socks代理的。
http = httplib2.Http()
main_url = 'http://mywebsite.com/get.aspx?id='+ id +'&rows=25'
response, content = http.request(main_url, 'GET', headers=headers)
main_cookie = response['set-cookie']
referer = 'http://google.com'
headers = {'Content-type': 'application/x-www-form-urlencoded', 'Cookie': main_cookie, 'User-Agent' : USER_AGENT, 'Referer' : referer}
那么,如何用urllib2来做同样的事情呢(获取cookie,然后在同一个网站上传递到下一个页面)?
谢谢!
1 个回答
3
可以使用 cookielib,它会像网页浏览器一样自动处理所有与 cookies 相关的工作。
示例:
import urllib2
import cookielib
cookie_jar = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
#Get the first page with the cookie, installing it in the cookie jar automatically
opener.open("http://yoursite.com/set-cookie")
#Get the second page, passing on the cookie in the cookiejar.
opener.open("http://yoursite.com/other")
#Alternatively, you can also install this opener as the default urllib2 opener:
urllib2.install_opener(opener)
#Now all urllib2 requests will use cookies:
urllib2.urlopen("http://yoursite.com/other")