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

求助:使用Requests库登录Google账户失败,无法提交表单数据

用Requests登录Google账户的问题解决思路

Google的登录系统做了极强的反爬和动态验证,直接用Requests模拟表单提交几乎不可能成功,核心原因包括:

  • 表单里的核心字段(如gxf、continue、xsrf令牌)都是动态生成的,每次请求都会变化,单纯抓一次表单数据复用完全没用
  • 登录流程中会触发reCAPTCHA验证码、两步验证,这些都是Requests这类无浏览器环境无法自动处理的
  • Google会校验浏览器指纹(比如JS渲染的参数、User-Agent的完整性),纯HTTP请求很容易被识别拦截

可行的替代方案

1. 使用自动化浏览器工具(Selenium/Playwright)

这类工具会模拟真实浏览器的行为,能处理JS渲染、Cookie管理,甚至可以手动介入处理验证码。示例(以Selenium为例):

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

driver = webdriver.Chrome()
driver.get('https://accounts.google.com/signin')

# 输入用户名
username_input = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'identifierId')))
username_input.send_keys('your_email@gmail.com')
driver.find_element(By.ID, 'identifierNext').click()

# 输入密码(若出现验证码需手动处理)
password_input = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, 'Passwd')))
password_input.send_keys('your_password')
driver.find_element(By.ID, 'passwordNext').click()

# 登录成功后提取Cookie,后续可用于Requests复用
cookies = driver.get_cookies()
driver.quit()

# 用Requests携带Cookie发起请求
import requests
session = requests.Session()
for cookie in cookies:
    session.cookies.set(cookie['name'], cookie['value'])
response = session.get('https://myaccount.google.com/')
print(response.text)

2. 采用官方OAuth 2.0 API(推荐)

这是Google官方支持的合法方式,不需要模拟登录,直接通过授权获取访问令牌来调用服务。示例:

from google_auth_oauthlib.flow import InstalledAppFlow
import requests

# 定义需要的权限范围,根据你的需求调整
SCOPES = ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email']

# 从Google Cloud控制台下载的credentials.json文件
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)

# 使用令牌调用用户信息API
response = requests.get(
    'https://www.googleapis.com/oauth2/v2/userinfo',
    headers={'Authorization': f'Bearer {creds.token}'}
)
print(response.json())

关于纯Requests模拟的说明

如果一定要尝试,步骤极其繁琐且稳定性极差:

  • 先发送GET请求到登录页面,解析HTML提取所有隐藏表单字段和Cookie
  • 携带所有字段POST提交用户名,处理可能的验证码跳转
  • 再POST提交密码,跟踪所有重定向并更新Cookie
    但即使完成这些,Google大概率会触发验证拦截,因为缺少浏览器环境的关键标识,不建议浪费时间在这种方式上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:53:10