You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合Selenium与Requests获取微软登录认证后的页面内容

问题根因

Selenium 控制的 Chrome 浏览器和你单独调用的 Requests 是完全隔离的两个会话:微软登录后下发的身份认证 Cookie 只存在于 Selenium 启动的浏览器进程中,Requests 发起请求时没有携带这些认证凭证,服务端判定为未登录状态,因此返回登录页内容。

修复方案

你只需要将 Selenium 登录后获取的 Cookie 同步给 Requests 会话即可,修改后的代码如下:

email = '你的微软账号邮箱'
password = '你的账号密码'

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver
from selenium.webdriver.common.by import By
import requests
from bs4 import BeautifulSoup

# 第一步:用Selenium完成登录
EMAILFIELD = (By.ID, "i0116")
PASSWORDFIELD = (By.ID, "i0118")
NEXTBUTTON = (By.ID, "idSIButton9")

browser = webdriver.Chrome()
browser.get('https://login.live.com')

WebDriverWait(browser, 10).until(EC.element_to_be_clickable(EMAILFIELD)).send_keys(email)
WebDriverWait(browser, 10).until(EC.element_to_be_clickable(NEXTBUTTON)).click()
WebDriverWait(browser, 10).until(EC.element_to_be_clickable(PASSWORDFIELD)).send_keys(password)
WebDriverWait(browser, 10).until(EC.element_to_be_clickable(NEXTBUTTON)).click()
# 等待登录完成,确保跳转到账号首页后再获取Cookie
WebDriverWait(browser, 10).until(EC.title_contains("Microsoft account | Home"))
WebDriverWait(browser, 10).until(EC.element_to_be_clickable(NEXTBUTTON)).click()

# 第二步:从Selenium中提取所有Cookie,同步给Requests
session = requests.Session()
for cookie in browser.get_cookies():
    session.cookies.set(cookie['name'], cookie['value'])
# 登录完成后可以关闭Selenium浏览器
browser.quit()

# 第三步:用带认证Cookie的Requests会话发起请求
req = session.get("https://account.microsoft.com/?lang=en-US&refd=account.live.com&refp=landing&mkt=EN-US")
soup = BeautifulSoup(req.text, 'html.parser')
print(soup.title)
print(req)

注意事项

  • 提取Cookie前必须确保Selenium已经完成全部登录流程,跳转到了认证后的页面,否则拿到的Cookie是未登录状态的无效凭证
  • 必须用requests.Session()来维护会话,不要直接用requests.get(),前者会自动存储和携带你设置的所有Cookie
  • 原示例代码中将email变量赋值为password是错误写法,运行前请替换为真实的微软账号信息

内容的提问来源于stack exchange,提问作者sirj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 19:36:01