【问题标题】:Open web page with custom cookies in Python在 Python 中使用自定义 cookie 打开网页
【发布时间】:2009-11-07 16:57:45
【问题描述】:
例如,我有 cookie
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()
如何使用我的预定义 cookie 做到这一点?
【问题讨论】:
标签:
python
cookies
urllib2
【解决方案1】:
您只需要几个步骤:
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()