【问题标题】:Selenium (Python) pattern matchingSelenium (Python) 模式匹配
【发布时间】:2019-07-06 10:09:53
【问题描述】:

目前正在编写一个使用 Selenium 填写在线表格的 Python 程序。填写并提交表单后,有 3 种可能的重定向。

我正在尝试编写一个函数来确定我被重定向到哪个页面。

我使用 3 个 try-except 块编写了一个函数,但我无法捕捉到 NoSuchElementException

def match():

    try:
         match = driver.find_element_by_id("hi")
         return 'condition 1'
    except NoSuchElementException:
        pass

    try:
        match = driver.find_element_by_id("hey")
        return 'condition 2'
    except NoSuchElementException:
        pass

    try:
        match = driver.find_element_by_id("hello")
        return 'condition 3'
    except NoSuchElementException:
        pass

    return 'none'

我收到以下异常

引发异常类(消息、屏幕、堆栈跟踪) selenium.common.exceptions.NoSuchElementException:消息:无法找到元素:[id="hi"]

旁注:有人知道在 Python 中进行模式匹配的更优雅的方法吗?

【问题讨论】:

  • 将以下行放在顶部:from selenium.common.exceptions import NoSuchElementException

标签: python selenium pattern-matching conditional-statements try-except


【解决方案1】:

引发异常是因为 selenium 在元素被事件加载到页面之前正在寻找元素。

更优雅的方法是使用selenium.webdriver.support.ui.WebDriverWait,它允许您保持执行流程直到满足条件(例如,dom 中存在元素)

进一步阅读:Selenium waits documentation

使用 xpath,您可以在条件中指定多个元素,因此当其中一个元素存在时,条件将被满足。 For example, see this answer

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

def match():        
    switcher = {
        'hi': 'condition 1',
        'hey': 'condition 2',
        'hello': 'condition 3'
    }

    try:

        # Wait for 10 seconds max until one of the elements is present or give up
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//div[@id = 'hi' or @id = 'hey' or @id = 'hello'"))
        )            
        return switcher[element.get_attribute('id')]
    except TimeoutException:
        return None    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多