【问题标题】:Check if element exists on page and continue if not using python [duplicate]检查页面上是否存在元素,如果不使用python则继续[重复]
【发布时间】:2022-02-01 20:02:12
【问题描述】:

试图解决一个问题,我需要检查一个元素是否在页面上(如果存在),如果不存在则执行一段代码,然后继续执行脚本。我遇到的问题是,如果元素没有出现,那么脚本将失败并显示“找不到元素”

我目前拥有的是:

form_error = s.driver.find_element_by_xpath("//div[contains(@class,'screen-new-error')]")
form_error = form_error.get_attribute('textContent')
form_error = form_error[6:].strip()
             
if form_error == "There was a problem with the Form":
   result = "FAIL"
else:
  result = "PASS"

【问题讨论】:

  • get_attribute 是做什么的?也许那里需要改变一些东西。

标签: python jquery selenium


【解决方案1】:

你有几个选择:

1.

from selenium.common.exceptions import NoSuchElementException        
def check_exists_by_xpath(xpath):
    try:
        webdriver.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False
    return True
  1. try/catch 内调用find_element

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 2021-01-23
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    相关资源
    最近更新 更多