2010-06-02 14 views
0

我該怎麼做?使用httlib2幫助轉換代碼以使用urllib2

訪問網站,檢索cookie,通過發送cookie信息訪問下一頁。這一切工作,但httplib2給我一個網站上的襪子代理太多問題。

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檢索,傳遞到同一站點上的下一頁)做同樣的事情?

謝謝。

回答

3

使用cookielib,它將像網絡瀏覽器一樣自動處理所有與cookie相關的工作。

例子:

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") 
+0

大,cookielib是要走的路!我是否必須使用opener.set_proxy()和opener.add_header()來獲得代理和頭文件支持?我現有的代碼略有差異。做法。它做了類似於req = urllib2.Request(url)的東西,如何在代碼中使用它?謝謝! – ThinkCode 2010-06-02 19:28:46

+0

一旦你創建了開瓶器,你也可以安裝開罐器作爲默認開罐器,以便它用於每個urllib2調用(以上添加): urllib2.install_opener(opener) – EnigmaCurry 2010-06-02 20:18:22

相關問題