使用Selenium WebDriver无法登录Google账户的问题求助
问题描述
使用Selenium自动登录Google账户时,页面触发“验证是否为本人”的人机验证,但手动输入账户凭据可正常登录,已排除IP及chromedriver运行问题。操作过程显示:自动输入账号密码后触发验证,手动操作则无此问题。
相关代码:
WebDriverWait(self, 15).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, 'input[type="email"]') ) ).send_keys(email) self.find_element(By.CSS_SELECTOR, 'div[id="identifierNext"]').click() WebDriverWait(self, 15).until( EC.element_to_be_clickable( (By.CSS_SELECTOR, 'input[type="password"]') ) ).send_keys(password) self.find_element(By.CSS_SELECTOR, 'div[id="passwordNext"]').click()
曾尝试使用Actions的move_to_element方法后再点击,无效果。
解决方案
Google的反自动化机制会识别Selenium的特征,以下是可行的规避方案:
使用Chrome用户配置文件
直接调用本地已登录过Google账号的Chrome配置文件,让浏览器处于已信任的环境,避免触发验证:from selenium.webdriver.chrome.options import Options from selenium import webdriver chrome_options = Options() # 替换为你的Chrome用户数据路径,Windows示例:C:\Users\你的用户名\AppData\Local\Google\Chrome\User Data # Mac示例:~/Library/Application Support/Google/Chrome/ chrome_options.add_argument(r"user-data-dir=C:\Users\XXX\AppData\Local\Google\Chrome\User Data") chrome_options.add_argument("--profile-directory=Default") # 指定默认配置文件 driver = webdriver.Chrome(options=chrome_options) driver.get("https://accounts.google.com")使用undetected-chromedriver绕过反爬
这个库专门针对Google等网站的反自动化机制优化,能隐藏Selenium的特征:- 安装库:
pip install undetected-chromedriver - 示例代码:
import undetected_chromedriver as uc from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By driver = uc.Chrome() driver.get("https://accounts.google.com") # 输入账号 WebDriverWait(driver, 15).until( EC.element_to_be_clickable((By.CSS_SELECTOR, 'input[type="email"]')) ).send_keys(email) driver.find_element(By.CSS_SELECTOR, 'div[id="identifierNext"]').click() # 输入密码 WebDriverWait(driver, 15).until( EC.element_to_be_clickable((By.CSS_SELECTOR, 'input[type="password"]')) ).send_keys(password) driver.find_element(By.CSS_SELECTOR, 'div[id="passwordNext"]').click()
- 安装库:
模拟真实用户输入行为
避免瞬间完成输入,模拟逐个字符输入+随机延迟,用回车键代替点击按钮,更贴近手动操作:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time import random # 输入账号 email_input = WebDriverWait(self, 15).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'input[type="email"]'))) for char in email: email_input.send_keys(char) time.sleep(random.uniform(0.1, 0.3)) # 随机延迟0.1-0.3秒 time.sleep(random.uniform(0.5, 1)) email_input.send_keys(Keys.ENTER) # 用回车代替点击下一步按钮 # 输入密码 password_input = WebDriverWait(self, 15).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'input[type="password"]'))) for char in password: password_input.send_keys(char) time.sleep(random.uniform(0.1, 0.3)) time.sleep(random.uniform(0.5, 1)) password_input.send_keys(Keys.ENTER)避免频繁操作
短时间内重复登录会被Google判定为异常行为,测试时需控制操作频率。
内容的提问来源于stack exchange,提问作者Egan Harvey
相关产品推荐
相关产品推荐

