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

能否使用Python Requests库填写表单实现谷歌账号登录?

用Python Requests实现谷歌账号登录(邮箱填写步骤)

可以用Requests实现,但谷歌登录页面有反爬验证和会话绑定机制,不能直接简单提交邮箱,需要按以下步骤处理:

核心步骤说明

  • 维护会话状态:必须用requests.Session()保持Cookie,否则谷歌会判定为异常请求。
  • 提取表单隐藏参数:谷歌登录表单包含多个必填隐藏字段(如GALX、continue等),这些参数需要从登录页面HTML中解析后随邮箱一起提交。
  • 模拟浏览器请求头:添加合理的User-Agent,避免被谷歌的反爬机制拦截。

修改后的代码示例

首先安装HTML解析库:

pip install beautifulsoup4

实现代码:

import requests
from bs4 import BeautifulSoup

def submit_email(email, timeout=10):
    # 初始化会话,保持Cookie
    session = requests.Session()
    # 设置模拟浏览器的请求头
    session.headers.update({
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
    })
    
    try:
        # 1. 获取登录页面,提取表单参数
        login_page = session.get("https://accounts.google.com/ServiceLogin?elo=1", timeout=timeout)
        soup = BeautifulSoup(login_page.text, "html.parser")
        
        # 提取所有隐藏表单字段
        form_data = {}
        for input_tag in soup.find_all("input", type="hidden"):
            if input_tag.get("name"):
                form_data[input_tag["name"]] = input_tag.get("value", "")
        
        # 填入邮箱字段(谷歌登录的邮箱字段名为identifier)
        form_data["identifier"] = email
        
        # 获取表单提交的目标URL
        login_form = soup.find("form", id="gaia_loginform")
        if not login_form:
            print("未找到登录表单,可能页面结构已更新")
            return None
        
        form_action = login_form["action"]
        if not form_action.startswith("http"):
            form_action = f"https://accounts.google.com{form_action}"
        
        # 2. 提交邮箱请求
        response = session.post(form_action, data=form_data, timeout=timeout)
        
        # 验证提交结果:若页面跳转至密码输入页则成功
        if "Enter your password" in response.text:
            print("邮箱提交成功,进入密码输入环节")
            return session  # 返回会话供后续密码提交使用
        else:
            print("邮箱提交失败,可能触发反爬或参数错误")
            return None
            
    except requests.exceptions.RequestException as e:
        print(f"请求出错:{e}")
        return None

# 调用示例
submit_email("your_email@example.com")

注意事项

  • 页面结构变化:谷歌会不定期更新登录页面的HTML结构,若代码失效,需重新检查表单字段名和提交接口。
  • 反爬拦截:如果频繁请求被拦截,可尝试添加随机延迟、更换IP或使用代理,但需遵守谷歌的服务条款。
  • 验证环节:若邮箱存在异常登录记录,谷歌会触发验证码(短信/2FA),此时纯Requests无法自动处理,需手动介入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:10:20