【问题标题】:Error handling not working on Selenium exception in Python错误处理不适用于 Python 中的 Selenium 异常
【发布时间】:2021-05-07 09:36:35
【问题描述】:

这是我的代码的一部分:

import time
from xpath_info import *
from credentials import *
from bs4 import BeautifulSoup
from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager as gdm
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException, WebDriverException

class NewtonClassroomAutomation:
    def __init__(self):
        self.driver = None

    def open_browser(self):

    # Newton Classroom link
        url ="https://griet.newtonclassroom.com/"

        # Installing gecko driver for opening firefox
        self.driver = webdriver.Firefox(executable_path=gdm().install())

        # Opening the url
        self.driver.get(url)
        print("Browser is now opened successfully")
        time.sleep(3)

    def enter_credentials(self):
    
        # Clicking on the 'Sign In with Google' button
        self.driver.find_element_by_xpath(google_login_button).click()
        time.sleep(3)

        # Entering the email address
        try:
            self.driver.find_element_by_xpath(email_text_box).send_keys(email)
            self.driver.find_element_by_xpath(next_button).click()
            print("Entered the email address")
            time.sleep(3)
        except NoSuchElementException:
            print("ERROR: The email address entered is either incorrect or does not exist.")

        # Entering the password
        self.driver.find_element_by_xpath(password_text_box).send_keys(password)
        self.driver.find_element_by_xpath(next_button).click()
        print("Entered the password")
        time.sleep(3)

即使添加了except 子句,我也没有得到print("ERROR: The email address entered is either incorrect or does not exist"),但我得到了 selenium 显示的错误。我不知道为什么在这种情况下错误处理不起作用。

这是我的代码显示的错误:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div[1]/div[1]/div[2]/div/div[2]/div/div/div[2]/div/div[1]/div/form/span/section/div/div/div[1]/div[1]/div/div/div/div/div[1]/div/div[1]/input

错误堆栈跟踪:

Traceback (most recent call last):
  File "d:\Python Automation & Webscraping\Newton Classroom Automation\main.py", line 61, in <module>
    my_classroom_bot.enter_credentials()
  File "d:\Python Automation & Webscraping\Newton Classroom Automation\main.py", line 42, in enter_credentials
    self.driver.find_element_by_xpath(password_text_box).send_keys(password)
  File "C:\Users\ravur\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\ravur\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\ravur\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\ravur\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div[1]/div[1]/div[2]/div/div[2]/div/div/div[2]/div/div[1]/div/form/span/section/div/div/div[1]/div[1]/div/div/div/div/div[1]/div/div[1]/input

【问题讨论】:

  • 如果异常属于NoSuchElementException btw 你的错误堆栈跟踪是什么?
  • 请包括 selenium 显示的错误。
  • Selenium 抛出了哪些错误,但您的 except 没有捕获到?
  • @ewong 我在问题中添加了错误
  • @Prophet NoSuchElementException

标签: python selenium web-scraping error-handling


【解决方案1】:

由于您的错误堆栈跟踪显示异常发生在 try 块之外。 它显示异常在第 42 行,以下行负责异常。 self.driver.find_element_by_xpath(password_text_box).send_keys(password)

而且这一行不在 try 块中。这就是为什么你得到异常而不是处理的消息。因为该行没有处理异常。

您正在使用 google 登录,它检测到 selenium 并阻止登录过程在密码页面上继续。这就是为什么它很可能找不到密码页面。

表单简单更改如下:

def enter_credentials(self):

    # Clicking on the 'Sign In with Google' button
    self.driver.find_element_by_xpath(google_login_button).click()
    time.sleep(3)

    # Entering the email address
    try:
        self.driver.find_element_by_xpath(email_text_box).send_keys(email)
        self.driver.find_element_by_xpath(next_button).click()
        print("Entered the email address")
        time.sleep(3)
    except NoSuchElementException:
        print("ERROR: The email address entered is either incorrect or does not exist.")

    # Entering the password
    try:
        self.driver.find_element_by_xpath(password_text_box).send_keys(password)
        self.driver.find_element_by_xpath(next_button).click()
        print("Entered the password")
        time.sleep(3)
    except NoSuchElementException:
    print("ERROR: The password field or the next button not found")

编辑:

添加显式等待:

导入:

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

在代码中使用这个

 WebDriverWait(self.driver,10).until(EC.element_to_be_clickable((By.XPATH, email_text_box))).send_keys(email)

而不是

self.driver.find_element_by_xpath(email_text_box).send_keys(email)

【讨论】:

  • 是的,现在我明白发生了什么,我将使用显式等待。非常感谢!
  • 你能告诉我如何在这里实现显式等待吗?
  • @PraneethRavuri 已编辑。检查代码。还要检查selenium-python.readthedocs.io/waits.html
猜你喜欢
  • 1970-01-01
  • 2020-04-25
  • 2017-07-15
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多