新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python如何獲取cookie
介紹下3種python獲取cookie的方法。

永勝網(wǎng)站建設公司創(chuàng)新互聯(lián)建站,永勝網(wǎng)站設計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為永勝近千家提供企業(yè)網(wǎng)站建設服務。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站建設要多少錢,請找那個售后服務好的永勝做網(wǎng)站的公司定做!
(1)借助handler
這種方法也是網(wǎng)上介紹最多的一種方法,但是用起來比較麻煩
from http import cookiejar from urllib import request class Craw(): def __init__(self): self.url = '' self.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) ' \ 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36' self.headers['Content-Type'] = 'application/x-www-form-urlencoded' def getCookies(self): cookie = cookiejar.CookieJar() handler = request.HTTPCookieProcessor(cookie) opener = request.build_opener(handler) response = opener.open(self.url) cookieValue = '' for item in cookie: cookieValue += item.name + '=' + item.value + ';' self.headers['Cookie'] = cookieValue response = requests.get(url=self.url) def getVerificationCode(self): img_url = '' imgResponse = requests.get(url=img_url,headers = self.headers) #直接使用headers即可 base64_jpg = base64.b64encode(imgResponse.content) return base64_jpg
(2)使用response headers的set_cookie
import requests
import re
class Crawler():
def getCookie(self):
response = requests.post(self.url)
set_cookie = response.headers['Set-Cookie']
array = re.split('[;,]',set_cookie)
cookieValue = ''
for arr in array:
if arr.find('DZSW_SESSIONID') >= 0 or arr.find('bl0gm1HBTB') >= 0:
cookieValue += arr + ';'(3)使用response的cookies屬性獲取
只寫getCookies方法,代碼如下:
import requests class Crawler(): def getCookie(self): response = requests.get(self.url) cookie_value = '' for key,value in response.cookies.items(): cookie_value += key + '=' + value + ';' self.headers['Cookie'] = cookie_value
新聞標題:創(chuàng)新互聯(lián)Python教程:python如何獲取cookie
URL網(wǎng)址:http://m.5511xx.com/article/coshpcj.html


咨詢
建站咨詢
