介紹下3種python獲取cookie的方法。
(1)借助handler
這種方法也是網(wǎng)上介紹最多的一種方法,但是用起來(lái)比較麻煩
fromhttpimportcookiejar
fromurllibimportrequest
classCraw():
def__init__(self):
self.url=''
self.headers['User-Agent']='Mozilla/5.0(WindowsNT6.3;Win64;x64)'\
'AppleWebKit/537.36(KHTML,likeGecko)Chrome/65.0.3325.162Safari/537.36'
self.headers['Content-Type']='application/x-www-form-urlencoded'
defgetCookies(self):
cookie=cookiejar.CookieJar()
handler=request.HTTPCookieProcessor(cookie)
opener=request.build_opener(handler)
response=opener.open(self.url)
cookieValue=''
foritemincookie:
cookieValue+=item.name+'='+item.value+';'
self.headers['Cookie']=cookieValue
response=requests.get(url=self.url)
defgetVerificationCode(self):
img_url=''
imgResponse=requests.get(url=img_url,headers=self.headers)#直接使用headers即可
base64_jpg=base64.b64encode(imgResponse.content)
returnbase64_jpg
(2)使用responseheaders的set_cookie
importrequests
importre
classCrawler():
defgetCookie(self):
response=requests.post(self.url)
set_cookie=response.headers['Set-Cookie']
array=re.split('[;,]',set_cookie)
cookieValue=''
forarrinarray:
ifarr.find('DZSW_SESSIONID')>=0orarr.find('bl0gm1HBTB')>=0:
cookieValue+=arr+';'
(3)使用response的cookies屬性獲取
只寫(xiě)getCookies方法,代碼如下:
importrequests
classCrawler():
defgetCookie(self):
response=requests.get(self.url)
cookie_value=''
forkey,valueinresponse.cookies.items():
cookie_value+=key+'='+value+';'
self.headers['Cookie']=cookie_value
以上內(nèi)容為大家介紹了python培訓(xùn)之如何獲取cookie,希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。