使用selenium+phantomjs无接口访问url,然后获取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"
url = "https://www.bing.com/"
driver.get(url)
# get cookie list
cookie_list=driver.get_cookies()
# format print cookie
for cookie in cookie_list:
cookie_dict[cookie['name']]=cookie['value']
使用cookielib:
(1)Python2
import cookielib
import urllib2
# Url = "https://et.xiamenair.com/xiamenair/book/findFlights.action?lang=zh&tripType=0&queryFlightInfo=XMN,PEK,2018-01-15"
Url = "https://www.bing.com/"
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
# skip SSL verify
import ssl
# set ignore ssl verify
ssl._create_default_https_context = ssl._create_unverified_context
if __name__ == '__main__':
# define cookiejar object
cookie = cookiejar.CookieJar()
# urllib.request HTTPCookieProcessor CookieHandler
handler=request.HTTPCookieProcessor(cookie)
# from CookieHandler create opener
opener = request.build_opener(handler)
# open url
response = opener.open('http://www.baidu.com')
# print cookie
for item in cookie:
print('Name = %s' % item.name)
print('Value = %s' % item.value)
使用请求:
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
html = requests.get(url, headers=Hostreferer,verify=False)
# cookie:DZSW_WSYYT_SESSIONID
if html.status_code == 200:
print(html.cookies)
for cookie in html.cookies:
print(cookie)