[Python]發送Cookies (Add header方式及CookieJra方式)

Add header方式

import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://zcgnotes.com/")

CookieJar方式

from cookielib import CookieJar
import urllib2
import urllib

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
formdata = { 'username' : username, 'password' : password }
encoded_data = urllib.urlencode(formdata)
response = opener.open('https://zcgnotes.com', encoded_data)
content = response.read()

可將open安裝在urllib2中,所以urllib2都會包含該cookies,方面login等操作

urllib2.install_opener(opener)