python 的cookies的几种获取和设置的方法
import requests
from urllib import request
from http import cookiejar
from selenium import webdriver
url = "https://www.douban.com/"
def cookie_get():
driver = webdriver.PhantomJS()
url = "http://www.baidu.com"
driver.get(url)
#获取cookies列表
cookie_dict={}
cookie_list = driver.get_cookies()
for cookie in cookie_list:
print("name = %s" % cookie['name'])
print("value = %s" % cookie['value'])
#cookie_dict[cookie['name']] = cookie['value']
#print(cookie_dict)
def cookies_get():
cookie = cookiejar.CookieJar()
handler = request.HTTPCookieProcessor(cookie)
opener = request.build_opener(handler)
response = opener.open("http://www.baidu.com")
for item in cookie:
print("name = %s" %item.name)
print("value = %s" %item.value)
def cookie_r():
url = "http://www.baidu.com"
s = requests.session()
r = s.get(url)
c = requests.cookies.RequestsCookieJar()
for item in s.cookies:
print(item)
#print(s.cookies)
def cookies_re():
global url
#url = "http://www.baidu.com"
headers = {'User-Agnet':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}
r = requests.get(url, headers=headers, stream=True)
print(r.url)
print(r.ok)
print(r.links)
print(len(r.text))
cookies_list = [] #列表
for key, value in r.cookies.items():
cookie = key + '=' + value
cookies_list.append(cookie)
#print(key,'=', value)
cookies_set = ','.join(cookies_list)
#print(r.cookies)
print("第二次获取")
cookies = cookies_set
print("自己合成的:", cookies)
headers = {
'User-Agnet':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
'cookies':cookies,
}
r = requests.get(url,headers=headers)
print(r.cookies)
cookies_re()
"""
print("第一个")
cookie_get()
print("第二个")
cookies_get()
"""
欢迎关注,获取更多使用技能