菜鸟IT的博客 >> Python
python request 获取cookies的3种方法
参考文章:https://www.jb51.net/article/196966.htm
# ——————————————————————
【1】利用selenium+phantomjs无界面浏览器的形式访问网站,再获取cookie值:
# ——————————————————————
from selenium import webdriver
driver=webdriver.PhantomJS()
url="https://et.xiamenair.com/xiamenair/book/findFlights.action?lang=zh&tripType=0&queryFlightInfo=XMN,PEK,2018-01-15"
driver.get(url)
# 获取cookie列表
cookie_list=driver.get_cookies()
# 格式化打印cookie
for cookie in cookie_list:
cookie_dict[cookie['name']]=cookie['value']
# ——————————————————————
【2】利用cookielib库获取::
# ——————————————————————
import cookielib
import urllib2
Url = "https://et.xiamenair.com/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
# ——————————————————————
【3】自己测试的::
# ——————————————————————
# 请求url
Res_kuaidi111=requests.get('https://www.111111111.com')
# 获取 Cookies
requests.utils.dict_from_cookiejar(Res_kuaidi100.cookies)
print("获取cookies:",requests.utils.dict_from_cookiejar(Res_kuaidi100.cookies))
菜鸟IT博客[2022.03.27-13:46] 访问:322