python中获取cookie的两种方法

第一种是利用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']
print(cookie_dict)



第二种是是用cookielib库获取:

# python2.7环境
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;


python3的使用方法如下:

# python3.6环境
from urllib import request
from http import cookiejar

if __name__ == '__main__':
    # 声明一个CookieJar对象实例来保存cookie
    cookie = cookiejar.CookieJar()
    # 利用urllib.request库的HTTPCookieProcessor对象来创建cookie处理器,也就CookieHandler
    handler=request.HTTPCookieProcessor(cookie)
    # 通过CookieHandler创建opener
    opener = request.build_opener(handler)
    # 此处的open方法打开网页
    response = opener.open('http://www.baidu.com')
    # 打印cookie信息
    for item in cookie:
        print('Name = %s' % item.name)
        print('Value = %s' % item.value)

你可能感兴趣的:(python)