import cookielib import urllib2 url = 'https://googel.com' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) headers = [] headers.append(('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36')) opener.addheaders = headers opener.open(url) urllib2.install_opener(opener)
透過將cookielib.cookieJar加入urllib2的opener,然後urllib2.install_opener把載有cookie的opener加入到urllib2中
之後再以urllib2發送的get/post request則包含cookies