求助:Python Selenium+PyAutoGUI实现谷歌账号自动登录失败
谷歌账号登录问题:Selenium+PyAutoGUI无法正常工作
问题详情
尝试用Python的Selenium登录谷歌账号,搭配PyAutoGUI库实现输入操作,但完全无效,试过网上各种方法都解决不了。问题截图显示PyAutoGUI无法完成输入操作的相关界面。
原代码
from logging import error from sys import executable import time import requests from selenium import webdriver import geckodriver_autoinstaller from selenium.webdriver.common.desired_capabilities import DesiredCapabilities if __name__ == "__main__": from selenium_stealth import stealth browser = webdriver.Chrome() stealth(browser, languages=["en-US", "en"], vendor="Google Inc.", platform="Win32", webgl_vendor="Intel Inc.", renderer="Intel Iris OpenGL Engine", fix_hairline=True, ) # get login page browser.get( "https://accounts.google.com/signin/v2/identifier?hl=ar&continue=https%3A%2F%2Fwww.google.com%3Fhl%3Dar&ec=GAlA8wE&flowName=GlifWebSignIn&flowEntry=AddSession") while True: # print(browser.page_source) pyautogui.write("my number") pyautogui.press('enter')
核心问题分析
- PyAutoGUI未导入:代码里完全没有
import pyautogui语句,直接调用必然报错。 - 无限循环逻辑错误:
while True会让输入操作无限重复,导致程序陷入死循环,无法正常执行后续步骤。 - PyAutoGUI不适用于谷歌登录:谷歌登录页有反爬检测,PyAutoGUI的模拟输入依赖系统焦点,不仅容易被拦截,还不稳定。
- 冗余代码:导入了
geckodriver_autoinstaller却使用Chrome浏览器,属于无效导入;requests、logging.error等模块也未用到。
修复后的解决方案
优先使用Selenium原生方法定位元素输入,搭配stealth规避部分检测,以下是可运行的示例代码:
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 from selenium_stealth import stealth if __name__ == "__main__": browser = webdriver.Chrome() # 配置stealth,需匹配你的本地硬件信息(可通过浏览器控制台查看) stealth(browser, languages=["en-US", "en"], vendor="Google Inc.", platform="Win32", webgl_vendor="Intel Inc.", # 替换为你的显卡厂商 renderer="Intel Iris OpenGL Engine", # 替换为你的显卡型号 fix_hairline=True, ) # 打开谷歌登录页 browser.get( "https://accounts.google.com/signin/v2/identifier?hl=ar&continue=https%3A%2F%2Fwww.google.com%3Fhl%3Dar&ec=GAlA8wE&flowName=GlifWebSignIn&flowEntry=AddSession") try: # 等待账号输入框加载完成(最多等待10秒) username_input = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.ID, "identifierId")) ) # 输入账号 username_input.send_keys("你的手机号/邮箱") # 点击下一步 browser.find_element(By.ID, "identifierNext").click() # 等待密码输入框加载 password_input = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.NAME, "Passwd")) ) # 输入密码 password_input.send_keys("你的密码") # 点击登录 browser.find_element(By.ID, "passwordNext").click() except Exception as e: print(f"执行出错: {str(e)}") browser.quit()
注意事项
- 谷歌反爬机制严格,即使使用上述代码,仍可能触发滑块验证、短信验证等人工校验,这是正常限制,无法完全绕过。
- 确保ChromeDriver版本与本地Chrome浏览器版本完全一致,否则会出现兼容性问题。
- 不要频繁自动化登录谷歌账号,容易触发账号安全限制。
内容的提问来源于stack exchange,提问作者Nader elsayed
相关产品推荐
相关产品推荐

