2009-11-07 32 views
5

例如自定義Cookie打開網頁,我有餅乾可以用Python

my_cookies = {'name': 'Albert', 'uid': '654897897564'} 

,我想打開網頁http://website.com

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) 
opener.addheaders.append(('User-agent', 'Mozilla/5.0 (compatible)')) 
opener.open('http://website.com').read() 

如何我可以與預定義的餅乾做到這一點?

回答

7

你只需要幾個步驟:

import urllib2 
import cookielib 

cp = urllib2.HTTPCookieProcessor() 
cj = cp.cookiejar 

# see cookielib.Cookie documentation for options description 
cj.set_cookie(cookielib.Cookie(0, 'a_cookie', 'a_value', 
           '80', False, 'domain', True, False, '/path', 
           True, False, None, False, None, None, None)) 
opener = urllib2.build_opener(urllib2.HTTPHandler(), 
           cp) 
opener.addheaders.append(('User-agent', 'Mozilla/5.0 (compatible)')) 
opener.open('http://website.com').read() 
+1

非常感謝,幫我:) – 2009-11-07 09:36:04