简体   繁体   English

使用 python 和 selenium 的自动化 Google 登录显示““此浏览器或应用程序可能不安全”

[英]Automation Google login with python and selenium shows ""This browser or app may be not secure""

I've tried login with Gmail or any Google services but it shows the following "This browser or app may not be secure" message:我尝试使用 Gmail 或任何 Google 服务登录,但它显示以下“此浏览器或应用程序可能不安全”消息:

错误图像

I also tried to do options like enable less secure app in my acc but it didn't work.我还尝试在我的账户中启用安全性较低的应用程序等选项,但它不起作用。 then I made a new google account and it worked with me.然后我创建了一个新的谷歌帐户,它对我有用。 but not with my old acc.但不是我的旧账户。

  1. how can i solve this?我该如何解决这个问题?
  2. How can i open selenium in the normal chrome browser not the one controlled by automated software?如何在普通 chrome 浏览器中打开 selenium 而不是由自动化软件控制的浏览器?

    This is my code这是我的代码
    from selenium.webdriver import Chrome
    from selenium.webdriver.chrome.options import Options


    browser = webdriver.Chrome()
    browser.get('https://accounts.google.com/servicelogin')
    search_form = browser.find_element_by_id("identifierId")
    search_form.send_keys('mygmail')
    nextButton = browser.find_elements_by_xpath('//*[@id ="identifierNext"]') 
    search_form.send_keys('password')
    nextButton[0].click() 

First of all don't use chrome and chromedriver.首先不要使用chrome和chromedriver。 You need to use Firefox.(if not installed) Download and install Firefox.您需要使用 Firefox。(如果未安装)下载并安装 Firefox。 Login to Google with normal Firefox.使用正常的 Firefox 登录 Google。

You need to show the Google site that you are not a robot.您需要向 Google 网站表明您不是机器人。 You can use code like this:你可以使用这样的代码:

from selenium import webdriver
import geckodriver_autoinstaller
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

geckodriver_autoinstaller.install()

profile = webdriver.FirefoxProfile(
    '/Users/<user name>/Library/Application Support/Firefox/Profiles/xxxxx.default-release')

profile.set_preference("dom.webdriver.enabled", False)
profile.set_preference('useAutomationExtension', False)
profile.update_preferences()
desired = DesiredCapabilities.FIREFOX

driver = webdriver.Firefox(firefox_profile=profile,
                           desired_capabilities=desired)

This can help you find your profile location. 可以帮助您找到您的个人资料位置。

But, why Firefox?但是,为什么是 Firefox?

Actually there is only one reason, chromedriver was coded by Google.实际上只有一个原因,chromedriver 是由 Google 编写的。 They can easily understand if it is a bot or not.他们可以很容易地理解它是否是机器人。 But when we add user data with Firefox, they cannot understand if there is a bot or not.但是当我们用 Firefox 添加用户数据时,他们无法理解是否有机器人。

You can fool Google like this.你可以这样欺骗谷歌。 It worked for me too.它也对我有用。 I tried very hard to do this.我非常努力地做到这一点。 Hope it will be resolved in you too.希望它也能在你身上得到解决。

This is working for me.这对我有用。 I found the solution from GitHub.我从 GitHub 找到了解决方案。

   from selenium import webdriver
   from selenium_stealth import stealth

   options = webdriver.ChromeOptions()
   options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36")
   options.add_experimental_option("excludeSwitches", ["enable-automation"])
   options.add_experimental_option('useAutomationExtension', False)
   options.add_argument('--disable-blink-features=AutomationControlled')
   driver = webdriver.Chrome(options=options)
   stealth(driver,
        languages=["en-US", "en"],
        vendor="Google Inc.",
        platform="Win32",
        webgl_vendor="Intel Inc.",
        renderer="Intel Iris OpenGL Engine",
        fix_hairline=True,
        )
   driver.get("https://www.google.com")

You can easily bypass the google bot detection with the undetected_chromedriver :您可以使用undetected_chromedriver轻松绕过 google bot 检测:

pip install undetected-chromedriver
pip install selenium

Credits: https://github.com/xtekky/google-login-bypass/blob/main/login.py学分: https://github.com/xtekky/google-login-bypass/blob/main/login.py

import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class Main:
  def __init_(self) -> None:
    self.url    = 'https://accounts.google.com/ServiceLogin'
    self.driver = driver = uc.Chrome(use_subprocess=True)
    self.time   = 10
    
  def login(self, email, password):
    WebDriverWait(self.driver, 20).until(EC.visibility_of_element_located((By.NAME, 'identifier'))).send_keys(f'{email}\n)
    WebDriverWait(self.driver, 20).until(EC.visibility_of_element_located((By.NAME, 'password'))).send_keys(f'{password}\n)
                                                                                
    self.code()
                                                                                  
  def code(self):
    # [ ---------- paste your code here ---------- ]
    time.sleep(self.time)                                                                                  
                                                                                  
if __name__ == "__main__":
  #  ---------- EDIT ----------
  email = 'email' # replace email
  password = 'password' # replace password
  #  ---------- EDIT ----------                                                                                                                                                         
 
  driver = Main()
  driver.login(email, password) 

From terminal pip install undetected-chromedriver then do the following steps, as shown below.从终端 pip 安装 undetected-chromedriver 然后执行以下步骤,如下所示。
NOTE: indent your code inside if name == main, as i have done, only then the program will work注意:如果 name == main 缩进你的代码,就像我所做的那样,只有这样程序才能工作

import undetected_chromedriver as uc
from time import sleep
from selenium.webdriver.common.by import By


if __name__ == '__main__':
    
    driver = uc.Chrome()
    driver.get('https://accounts.google.com/')

    # add email
    driver.find_element(By.XPATH, '//*[@id="identifierId"]').send_keys(YOUR EMAIL)
    driver.find_element(By.XPATH, '//*[@id="identifierNext"]/div/button/span').click()
    sleep(3)
    driver.find_element(By.XPATH, '//*[@id="password"]/div[1]/div/div[1]/input').send_keys(YOUR PASSWORD)
    driver.find_element(By.XPATH, '//*[@id="passwordNext"]/div/button/span').click()
    sleep(10)


You can use undetected-chromedriver from github您可以使用来自 github 的未检测到的chromedriver

import undetected_chromedriver as uc
from selenium import webdriver

options = uc.ChromeOptions()
options.add_argument("--ignore-certificate-error")
options.add_argument("--ignore-ssl-errors")
# e.g. Chrome path in Mac =/Users/x/Library/xx/Chrome/Default/
options.add_argument( "--user-data-dir=<Your chrome profile>")
driver = uc.Chrome(options=options)
url='https://accounts.google.com/servicelogin'
driver.get(url)

Your first import need to be undetected Chrome driver.您的第一次导入需要未被检测到的 Chrome 驱动程序。

Firstly, I would ask you to use the undetected_chromedriver module首先,我会要求你使用 undetected_chromedriver 模块

I have found some issues with the original repo so I have forked a repo that supports user_data_dir and also allows you to provide custom chromedriver path as well.我发现原始存储库存在一些问题,因此我分叉了一个支持 user_data_dir 并且还允许您提供自定义 chromedriver 路径的存储库。

Uninstall the old module and install this by using git clone and then go the folder and run python setup.py install卸载旧模块并使用 git 克隆安装它,然后使用 go 文件夹并运行 python setup.py install

Forked repo link: https://github.com/anilabhadatta/undetected-chromedriver分叉回购链接: https://github.com/anilabhadatta/undetected-chromedriver

Import the latest undetected_chromdriver module:导入最新的 undetected_chromdriver 模块:

import undetected_chromedriver.v2 as ucdriver将 undetected_chromedriver.v2 导入为 ucdriver

For using user_data_dir feature write:对于使用 user_data_dir 功能写入:

options.user_data_dir = "path_to _user-data-dir"

instead of using this而不是使用这个

options.add_argument(f"user_data_dir={path_to _user-data-dir}")

profile_directory name is the same as how we write in selenium profile_directory 名称与我们在 selenium 中的写法相同

options.add_argument(f"--profile-directory=Default")

For using custom chrome path,对于使用自定义 chrome 路径,

options.binary_location = chrome_path

For using custom chromedriver path,对于使用自定义 chromedriver 路径,

driver = ucdriver.Chrome(executable_path=f'{path_to_chromedriver}', options=options)

Recently Google made some changes for which the authentication part didn't work.最近谷歌做了一些修改,认证部分不起作用。

I have tested this in Python 3.9.0, there are reports that it may not work correctly in 3.10.0我在 Python 3.9.0 中对此进行了测试,有报告称它在 3.10.0 中可能无法正常工作

And this is tested in both Windows and Linux.这在 Windows 和 Linux 中进行了测试。

Final Code:最终代码:

def load_chrome_driver(headless):
    chrome_loc = "/home/ubuntu/Downloads/chromium-browser/"
    chrome_path = chrome_loc + "chrome"
    chromedriver_path = chrome_loc + "chromedriver"
    user_data_dir = "/home/ubuntu/.config/chromium/custom_user"
    options = webdriver.ChromeOptions()
    if headless:
        options.add_argument('headless')
    options.add_argument('--profile-directory=Default')
    options.add_argument("--start-maximized")
    options.add_argument('--disable-gpu')
    options.add_argument('--no-sandbox')
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument('--log-level=3')
    options.binary_location = chrome_path
    options.user_data_dir = user_data_dir
    driver = ucdriver.Chrome(
        executable_path=chromedriver_path, options=options)
    driver.set_window_size(1920, 1080)
    driver.set_window_position(0, 0)
    return driver

Google is detecting that you're using a bot. Google 正在检测您正在使用机器人。 You must first of all add this snippet of config (convert it to python since i wrote it in java):您必须首先添加此配置片段(将其转换为 python,因为我是用 java 编写的):

    options.addArguments("--no-sandbox");
            options.addArguments("--disable-dev-shm-usage");
            options.addArguments("--disable-blink-features");
            options.setExperimentalOption("excludeSwitches", Arrays.asList("enable-automation"));
            options.addArguments("--disable-blink-features=AutomationControlled");
            options.addArguments("--disable-infobars");

        options.addArguments("--remote-debugging-port=9222");

options.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);

driver.executeScript("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})");

The last instruction is the key one, when you launch Selenium, the navigator var of Chrome is set to 'true', that means that the browser is controlled by a bot, setting it with JS to undefined renders it a "normal browser" in view of Google.最后一条指令是关键,当你启动 Selenium 时,Chrome 的 navigator var 设置为 'true',这意味着浏览器是由 bot 控制的,用 JS 将其设置为 undefined 使其成为“普通浏览器”谷歌的视图。 Another important thing you should do is to change the HEX of the chromedriver binary, i can PM you my already modified one (ubuntu environment), if you trust me obv.您应该做的另一件重要的事情是更改 chromedriver 二进制文件的 HEX,如果您相信我 obv,我可以将我已经修改过的一个(ubuntu 环境)发给您。

If you'd prefer Chrome over Firefox, the way to go around Googles automation detection is by using the undetected_chromedriver library.如果您更喜欢 Chrome 而不是 Firefox,那么围绕 Google 自动化检测的 go 的方法是使用undetected_chromedriver库。 You can install the package using pip install undetected-chromedriver .您可以使用pip install undetected-chromedriver Once your driver object is initiated you can simply use selenium to operate the driver afterwards.启动驱动程序 object 后,您可以简单地使用 selenium 来操作驱动程序。

# initiate the driver with undetetcted_chromedriver
import undetected_chromedriver.v2 as uc
driver = uc.Chrome()

# operate the driver as you would with selenium
driver.get('https://my-url.com') 

# Example use of selenium imports to be used with the driver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By

try:
    driver.find_element(By.XPATH, '//*[@id="my-id"]').click()
except NoSuchElementException:
    print("No Such Element Exception")

Note: the login of Google is a popup, so don't forget to swap window handles to the popup to login and then afterwards to switch back to the main window.注意:Google 的登录是一个弹出窗口,所以不要忘记将 window 句柄交换到弹出窗口以登录,然后切换回主 window。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 selenium python 时出现“此浏览器或应用程序可能不安全”错误 - “This browser or app may not be secure” error when using selenium python 如何处理浏览器或应用程序可能不是 Web 驱动程序 Selenium python 的安全问题? - How to handle browser or app may not be secure issue with web driver Selenium python? 谷歌自动化与 selenium 和 python - Automation of google with selenium and python 我们可以用纯Python urllib登录网站,修改一些表单值,然后提交吗? (没有 Selenium 浏览器自动化) - Can we login on a website with pure Python urllib, modify some form values, and submit? (without Selenium browser automation) 自动化 Spotify 登录使用 Selenium、Python - Automation Spotify Login using Selenium, Python Gmail 中的错误通过谷歌搜索通过 Chromedriver 使用 Selenium Python 自动登录 - Error in Gmail Login by google searching Automation via Chromedriver using Selenium Python 使用 selenium python 的浏览器自动化:现在无法找到要加入的元素 google meet - Browser automation With selenium python : unable to locate element for join now google meet Python Selenium 谷歌登录机器人 - Python Selenium Google login bot 用于 selenium 浏览器自动化的 Flask Web 应用程序输入 - Flask web-app input for selenium browser automation Python Selenium Web Automation 如何单击登录按钮 - Python Selenium Web Automation How Do You Click A Login Button
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM