使用 Python 登录 Gmail 并检测登录失败

时间:2021-02-06 11:23:12

标签: python selenium authentication google-account python-webbrowser

我知道很多人都问过类似的问题,但是我想知道如何使用 python 登录到 gmail(或谷歌帐户)。我已经有一个代码(见下文),可以使用 selenium 将用户登录到 gmail。但是我注意到了一些问题。

  1. 浏览器在程序停止/关闭时关闭。
  2. 它无法检测到登录失败。

这两个问题确实需要解决,我才能在我的项目上工作。我不介意使用像 pyautogui 这样的硒以外的东西来打开谷歌。但是,它需要能够检测到登录失败然后关闭浏览器,如果登录成功,浏览器应该保持打开状态供用户使用。

我的代码:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

def gmail_login(username, password):
    gmailId = username
    passWord = password
    driver = webdriver.Chrome(ChromeDriverManager().install())
    try:
        driver.get(r'https://accounts.google.com/signin/v2/identifier?continue=' + \
                   'https%3A%2F%2Fmail.google.com%2Fmail%2F&service=mail&sacu=1&rip=1' + \
                   '&flowName=GlifWebSignIn&flowEntry = ServiceLogin')
        driver.implicitly_wait(3)

        loginBox = driver.find_element_by_xpath('//*[@id ="identifierId"]')
        loginBox.send_keys(gmailId)

        nextButton = driver.find_elements_by_xpath('//*[@id ="identifierNext"]')
        nextButton[0].click()

        passWordBox = driver.find_element_by_xpath(
            '//*[@id ="password"]/div[1]/div / div[1]/input')
        passWordBox.send_keys(passWord)

        nextButton = driver.find_elements_by_xpath('//*[@id ="passwordNext"]')
        nextButton[0].click()

    except:
        driver.close()


gmail_login("email@gmail.com", "Password")

在程序完成后我很难检查 url 是否等于登录的 url 但这并没有真正起作用,现在我没有想法了。

3 个答案:

答案 0 :(得分:2)

于 2021 年 2 月 14 日更新


我能够提取此错误消息:

enter image description here

使用此代码:

signin_failure = driver.find_elements_by_xpath("//*[contains(text(),'Couldn’t sign you in')]")
if signin_failure[1].text == 'Couldn’t sign you in':
   print('something went wrong')

在正常的 gmail 登录中,您将收到以下两条错误消息之一:

  • 找不到您的 Google 帐户
  • 密码错误。重试或点击忘记密码来重置它

获取这些错误消息的 XPATH 是:

wrong_email = driver.find_elements_by_xpath("//*[contains(text(),'Couldn’t find your Google Account')]")

wrong_password = driver.find_elements_by_xpath("//*[contains(text(),'Wrong password. Try again or click Forgot password to reset it')]")

如果您想在出现错误消息(例如无法登录)后关闭浏览器,请添加 driver.close() 语句。

signin_failure = driver.find_elements_by_xpath("//*[contains(text(),'Couldn’t sign you in')]")
if signin_failure[1].text == 'Couldn’t sign you in':
   print('something went wrong')
   driver.close()

如果您想让浏览器保持打开状态,请不要使用 driver.close() 语句,而是添加此 experimental_option

chrome_options.add_experimental_option("detach", True)

我也能够抛出这些错误消息:

signin_failure = driver.find_elements_by_xpath("//*[contains(text(),'Couldn’t sign you in')]")

# this message was throw when the next button was clicked prior to entering a username
no_input = driver.find_elements_by_xpath("//*[contains(text(),'Enter a valid email of phone number')]")

伪代码:

您可以这样做,但您可能需要在测试时调整代码。

def gmail_login(username, password):
    driver = webdriver.Chrome(ChromeDriverManager().install())
    try:
        driver.get(r'https://accounts.google.com/signin/v2/identifier?continue=' + \
                   'https%3A%2F%2Fmail.google.com%2Fmail%2F&service=mail&sacu=1&rip=1' + \
                   '&flowName=GlifWebSignIn&flowEntry = ServiceLogin')
        driver.implicitly_wait(3)

        loginBox = driver.find_element_by_xpath('//*[@id ="identifierId"]')
        loginBox.send_keys(username)

        nextButton = driver.find_elements_by_xpath('//*[@id ="identifierNext"]')
        nextButton[0].click()

        wrong_email = driver.find_elements_by_xpath("//*[contains(text(),'Couldn’t find your Google Account')]")

        # you need to check this slice
        if wrong_email[1].text == 'Couldn’t find your Google Account':
            print('something went wrong')
            driver.close()

        else:
            passWordBox = driver.find_element_by_xpath('//*[@id ="password"]/div[1]/div / div[1]/input')
            passWordBox.send_keys(password)

            nextButton = driver.find_elements_by_xpath('//*[@id ="passwordNext"]')
            nextButton[0].click()

            wrong_password = driver.find_elements_by_xpath("//*[contains(text(),'Wrong password. Try again or click Forgot password to reset it')]")

            # you need to check this slice
            if wrong_password[1].text == 'Wrong password. Try again or click Forgot password to reset it':
                print('something went wrong')
                driver.close()

    except:
        driver.close()

原帖


Google 禁止使用自动脚本登录 Gmail。我曾尝试使用 selenium,但收到此警告

Cannot sign-in

当我点击了解详情时,我收到了这条消息。

enter image description here

请注意这一行: 通过软件自动化而非人工进行控制

以下是他们讨论解决此 Google 直接登录问题的其他问题:

答案 1 :(得分:1)

您应该查看 Gmail API 以进行编程访问,它比尝试像 selenium 那样驱动 UI 会工作得更好。 https://developers.google.com/gmail/api/quickstart/python

答案 2 :(得分:1)

我现在没有时间编写代码,但是:

要使浏览器保持打开状态,只需删除 driver.close() 函数,这就是它在程序到达时停止的原因。

要解决您的问题,只需尝试成功登录和失败登录,在两者中查找以独特方式指示事件之一的 WebElement,然后将 driver.close() 放在 if 声明中只有在登录后selenium在viewport中找到WebElement(失败),否则不让它执行指令。

就这么简单。