selenium提取cookies与requests配合使用

import pprint
import requests
from selenium import webdriver
path = 'chromedriver.exe'
browser = webdriver.Chrome(path)
browser.get('http://www.baidu.com')
cookies = browser.get_cookies()

pprint.pprint(cookies)
# {'domain': '.baidu.com',
#   'expiry': 1737379179,
#   'httpOnly': False,
#   'name': 'ZFY',
#   'path': '/',
#   'sameSite': 'None',
#   'secure': True,
#   'value': 'eJCSSWSqo74wC7xE13DOGn:BdMnZpA3WIdcFox2ah:BoY:C'}
# 真正有用的是name和value,在cookie中相当于ZFY=eJCSSWSqo74wC7xE13DOGn:BdMnZpA3WIdcFox2ah:BoY:C

# 提取字典形式的cookie
cookie_dit={}
for dic in cookies:
    key = dic['name']
    value = dic['value']
    cookie_dit[key]=value
print(cookie_dit)
# cookie_dit = {dic['name']:dic['value'] for dic in cookies}  字典生成式
# 当你有一个字典形式的cookie,可以直接把这个字典作为参数传递给requests

headers = {
    
}
requests.get("xxx",headers=headers,cookies=cookie_dit)

你可能感兴趣的:(selenium,测试工具)