运行Selenium脚本后Google Chrome登录失败问题求助
Selenium登录Google账号触发人机验证的解决方案
运行下方Python脚本登录Google账号时,触发了人机验证(错误截图如下),试过加time.sleep()但Firefox上还是报错,相关代码如下,求技术帮助:

相关代码
# 打开Gmail登录页面 driver = uc.Chrome(use_subprocess=True,service = service) driver.get("https://accounts.google.com/signin") # 输入邮箱并点击下一步 email_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="identifierId"]'))) email_field.send_keys(email+str('\n')) # next_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="identifierNext"]/div/button'))) # next_button.click() # 输入密码并提交 password_field = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, 'Passwd'))) password_field.send_keys(password+str('\n')) # submit_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="passwordNext"]/div/button'))) # submit_button.click() time.sleep(3)
解决建议
- 别用回车键替代点击按钮,Google反爬会识别这种非人工操作,把注释的点击按钮代码恢复,用
next_button.click()和submit_button.click()完成步骤,去掉send_keys('\n') - 使用undetected-chromedriver时,添加模拟真实用户的配置,规避自动化检测:
options = uc.ChromeOptions() # 设置真实UA options.add_argument("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") # 禁用自动化特征标记 options.add_argument("--disable-blink-features=AutomationControlled") driver = uc.Chrome(options=options, use_subprocess=True, service=service) - 全程用
WebDriverWait等待元素状态,别依赖time.sleep(),比如点击下一步后,等待密码框可交互再输入 - 如果用Firefox,改用
undetected-geckodriver并配置隐私参数:from undetected_geckodriver import Firefox from selenium.webdriver.firefox.options import Options options = Options() options.set_preference("dom.webdriver.enabled", False) options.set_preference("useAutomationExtension", False) driver = Firefox(options=options) - 可以尝试加载已登录的浏览器配置文件,让会话更接近真实用户(以Chrome为例):
options.add_argument(r"user-data-dir=C:\Users\你的用户名\AppData\Local\Google\Chrome\User Data") options.add_argument(r"profile-directory=Default")
内容的提问来源于stack exchange,提问作者Oatman Reynaldo
相关产品推荐
相关产品推荐

