【问题标题】:Find element using if else or try except in Python Selenium在 Python Selenium 中使用 if else 或 try except 查找元素
【发布时间】:2020-11-25 09:25:07
【问题描述】:

我很困惑检查元素是否存在的最佳和正确方法?使用try-exceptif-else?尝试查找元素时,两者有什么区别和优缺点?

def find_logo():
    return driver.find_elements(By.CSS_SELECTOR, ".navbar-brand [src='/logo/logo.svg']")

if find_logo(): 
    print("Found the logo")
else:
    print("Cannot find the logo")

所以用 try 会得到相同的结果,除了:

def find_logo():
    return driver.find_element(By.CSS_SELECTOR, ".navbar-brand [src='/logo/logo.svg']")

try:
    find_logo()
    print("Found the logo")
except NoSuchElementException:
    print("Cannot find the logo")

两者的工作方式似乎相同,但哪种方法是正确的?

【问题讨论】:

  • 问题本身不正确,因为在第一种情况下find_logo 返回list,在第二种情况下 - 单个 WebElement。所以它不是关于什么方法是正确的,而是用户想要得到什么输出
  • 哦,是的,问题是如果它是find_element 并且徽标图像不存在,那么它总是会返回错误,无法找到这样的元素,并且不会到达 else 语句。
  • Sooo...显然,在这种情况下您需要使用try/except

标签: python selenium if-statement try-catch findelement


【解决方案1】:

典型地,if-elsetry-except 逻辑都需要修改,但它们需要根据您的用例来实现。


if find_logo()if find_logo() 将始终成功,因为您使用了 def find_logo(),它可能根本不会返回任何元素。在这种情况下,您可能需要检查 list 的大小是否不是 0


try: find_logo(): try: find_logo() 似乎在没有 特定 元素的情况下通过 NoSuchElementException 校验与另一个更好地组织在一起找到了。


代码优化

但是根据最佳实践,在查找元素时,您需要将WebDriverWait 诱导为visibility_of_element_located(),您可以使用以下逻辑:

try:
    WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".navbar-brand [src='/logo/logo.svg']")))
    print("Found the logo")
except TimeoutException:
    print("Cannot find the logo")
    

注意:您必须添加以下导入:

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

【讨论】:

  • 感谢您的精彩解释,但是我还有一个问题,为什么 WebDriverWait 的元素可见性比 find_element 更好?不一样还是……?
【解决方案2】:

在第一种情况下,函数返回一个列表,在第二种情况下,函数返回您正在寻找的网页元素。

【讨论】:

  • 哦,是的,问题是如果它是find_element 并且徽标图像不存在,那么它总是会返回错误,无法找到这样的元素,并且不会到达 else 语句。
猜你喜欢
  • 1970-01-01
  • 2021-03-15
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 2012-11-06
  • 1970-01-01
相关资源
最近更新 更多