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

yueyue · February 15, 2022 · 1656 hits

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
No Reply at the moment.
需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up