Python使用undetected chromedriver无头模式无法通过谷歌身份验证登录
谷歌账号登录无头模式运行失败解决方案
核心原因
旧版Chrome无头模式存在明显的自动化指纹特征,谷歌的风控系统可以直接识别,加上原有配置中的参数冲突、UA版本过旧,都会触发不安全浏览器提示。
可行解决步骤
- 替换旧版无头模式参数:将原有的
--headless替换为Chrome 112及以上版本支持的新版无头模式参数--headless=new,该模式的浏览器指纹和普通可视模式几乎完全一致,可绕过大部分基础检测。 - 移除冲突参数:删除
--incognito隐身模式参数,该参数和自定义用户数据目录--user-data-dir存在配置冲突,且隐身模式本身的特征更容易触发风控。 - 更新或移除自定义UA:原有代码使用的Chrome 60版本UA是2017年的老旧版本,本身就会被标记为不安全。可直接删除手动设置UA的代码,让undetected-chromedriver自动匹配当前Chrome版本的正确UA,也可以替换为和你使用的Chrome大版本完全一致的UA字符串。
- 添加反检测补充参数:在ChromeOptions中加入以下参数进一步抹除自动化特征:
--no-first-run --no-default-browser-check --start-maximized --disable-blink-features=AutomationControlled
修改后参考代码
from seleniumwire.undetected_chromedriver.v2 import Chrome, ChromeOptions from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from pathlib import Path def execute_authorization(url, email, password): # 创建空配置文件 Path("./chrome_profile").mkdir(parents=True, exist_ok=True) Path('./chrome_profile/First Run').touch() options = {} chrome_options = ChromeOptions() chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument('--user-data-dir=./chrome_profile/') # 改用新版无头模式 chrome_options.add_argument('--headless=new') # 补充反检测参数 chrome_options.add_argument('--no-first-run') chrome_options.add_argument('--no-default-browser-check') chrome_options.add_argument('--start-maximized') chrome_options.add_argument('--disable-blink-features=AutomationControlled') browser = Chrome(seleniumwire_options=options, options=chrome_options) wait = WebDriverWait(browser, 10) browser.get(url) wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="identifierId"]'))) browser.find_element(By.XPATH, '//*[@id="identifierId"]').send_keys(email) wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="identifierNext"]/div/button'))) browser.find_element(By.XPATH, '//*[@id="identifierNext"]/div/button').click() wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="password"]/div[1]/div/div[1]/input'))) browser.find_element(By.XPATH, '//*[@id="password"]/div[1]/div/div[1]/input').send_keys(password) wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="passwordNext"]/div/button'))) browser.find_element(By.XPATH, '//*[@id="passwordNext"]/div/button').click() wait_for_correct_current_url(wait) return browser.current_url
内容的提问来源于stack exchange,提问作者maciejka
相关产品推荐
相关产品推荐

