Python3获取cookie常⽤三种⽅案
⽅案⼀:
利⽤selenium+phantomjs⽆界⾯浏览器的形式访问⽹站,再获取cookie值:
from selenium import webdriver
driver=webdriver.PhantomJS()
url="et.xiamenair/xiamenair/book/findFlights.action?lang=zh&tripType=0&queryFlightInfo=XMN,PEK,2018-01-15"
<(url)
# 获取cookie列表
cookie__cookies()
# 格式化打印cookie
for cookie in cookie_list:
cookie_dict[cookie['name']]=cookie['value']
⽅案⼆:
利⽤cookielib库获取:
(1)Python2
import cookielib
import urllib2
Url = "et.xiamenair/xiamenair/book/findFlights.action?lang=zh&tripType=0&queryFlightInfo=XMN,PEK,2018-01-15"
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
resp = urllib2.urlopen(Url)
for index, cookie in enumerate(cj):
print '[',index, ']',cookie
(2)Python3
from urllib import request
from http import cookiejar
#跳过SSL验证证书
import ssl
#设置忽略SSL验证
ssl._create_default_https_context = ssl._create_unverified_context
if __name__ == '__main__':
#声明⼀个CookieJar对象实例来保存cookie
cookie = cookiejar.CookieJar()
#利⽤quest库的HTTPCookieProcessor对象来创建cookie处理器,也就CookieHandler
handler=request.HTTPCookieProcessor(cookie)
#通过CookieHandler创建opener
opener = request.build_opener(handler)
#此处的open⽅法打开⽹页
response = opener.open('www.baidu')
#打印cookie信息
for item in cookie:
print('Name = %s' % item.name)
print('Value = %s' % item.value)
⽅案三:
selenium获取cookie利⽤requests库获取:
Python3
def getCookie():
url = "****"
Hostreferer = {
#'Host':'***',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36' }
#urllib或requests在打开https站点是会验证证书。简单的处理办法是在get⽅法中加⼊verify参数,并设为False
html = (url, headers=Hostreferer,verify=False)
#获取cookie:DZSW_WSYYT_SESSIONID
if html.status_code == 200:
kies)
for cookie kies:
print(cookie)
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论