在Python中使用自定义Cookie打开网页
比如说,我有一些 cookies
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()
我该怎么用我预先定义好的 cookies 来做到这一点呢?
1 个回答
8
你只需要再做几个步骤:
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()