Python requests 调用接口使用 selenium 登录页面 cookie

yueyue · 2022年02月15日 · 1625 次阅读

UI 自动化和 API 自动化有时候需要并行,涉及到接口请求需要传递登录 cookie 时,可利用 selenium 登录页面后获取 cookie 传递给 API 使用

from selenium import webdriver
import requests
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--headless')
# self.driver = webdriver.Chrome()
chrome_options.add_argument("--no-sandbox")
driver = webdriver.Chrome(options=chrome_options)
driver.maximize_window()
driver.find_element_by_xpath('').send_keys("username")
driver.find_element_by_xpath('').send_keys("password")
driver.find_element_by_xpath('').click()
# 获取登录cookie
co = driver.get_cookies()
cookies = {}
for cookie in co:
    cookies[cookie['name']] = cookie['value']

requests.post(url="url", cookies=cookies)  # 请求接口传递cookie
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册