Python 如何优雅地处理selenium中的NoSuchElementElement异常?
我有大约20个元素要通过xpath查找。我在用这个Python 如何优雅地处理selenium中的NoSuchElementElement异常?,python,python-3.x,selenium,Python,Python 3.x,Selenium,我有大约20个元素要通过xpath查找。我在用这个 e1 = element.find_element_by_xpath('.//div[contains(@class, "myclass")]').text 当找不到元素时,它会抛出NoTouchElementException 一种解决方案是使用:find\u elements\u by\u xpath e1 = element.find_elements_by_xpath('.//div[contains(@class
e1 = element.find_element_by_xpath('.//div[contains(@class, "myclass")]').text
当找不到元素时,它会抛出NoTouchElementException
一种解决方案是使用:
find\u elements\u by\u xpath
e1 = element.find_elements_by_xpath('.//div[contains(@class, "myclass")]')
# Then check for length
if len(e1) > 0:
text1 = e1[0].text
一个元素有三行代码。如果我使用
try
,除了
之外,还有60行代码
对于这样一个琐碎的任务,我们需要更多
如何优雅地处理这个问题?另外,有没有办法直接从xpath中查找文本
,而不是执行元素
# This should return text inside of that element
text = element.find_element_by_xpath('.//div[contains(@class, "myclass")]/text()')
# This should return text inside of that element
text = element.find_element_by_xpath('.//div[contains(@class, "myclass")]/text()')
从本质上讲,您正在编写一些可能导致异常的代码,因此try/except是正确的处理方法。它不需要60行代码,只需编写和调用这样的函数,这就是我要做的:
def text_if_element_found_by_xpath(xpath):
try:
text = driver.find_element_by_xpath(xpath).text
return text
except NoSuchElementException:
return ""
那么测试中的代码就是简单的
text1 = text_if_element_found_by_xpath(xpath1)
text2 = text_if_element_found_by_xpath(xpath2)
...
关于这一点:
另外,有没有办法直接从xpath中查找文本
,而不是执行元素
# This should return text inside of that element
text = element.find_element_by_xpath('.//div[contains(@class, "myclass")]/text()')
# This should return text inside of that element
text = element.find_element_by_xpath('.//div[contains(@class, "myclass")]/text()')
我认为element.text
是最好的方法find\u element\u by_xpath()
将始终返回元素(或导致异常),而不是文本/字符串,因此没有xpath可以为您获取文本
即使它可以工作,您的示例代码会比这更好吗
要做到这一点,最简单也是最佳实践的方法是使用。如您所建议的那样使用find_elements()
,只需将其包装在一个函数中,以使其更易于重用,保持代码干燥,并使代码更易于阅读
与其将定位器仅限于XPath,不如在方法中使用By
from selenium.webdriver.common.by import By
def get_text(element, locator):
elements = element.find_elements(locator)
if len(elements) > 0:
return elements[0].text
return ""
注意:在此处返回“”(空字符串),而不是None
。如果您在未找到时返回None
,则在处理返回时必须检查None
,否则会出现异常
那你就这样称呼它
e1 = get_text(element, (By.XPATH, './/div[contains(@class, "myclass")]'))
或者更好的是,使用CSS选择器,因为它更快、支持更好,并且在这种情况下,不太可能给您带来意外的元素
e1 = get_text(element, (By.CSS_SELECTOR, "div.myclass"))
另外,您不能在浏览器的XPath中使用/text()
,因为浏览器只支持XPath 1.0,而/text()
在更高版本中。python中没有null
这类东西。null的等价物是None
@jeffoops。我不擅长python,谢谢你指出这一点。你说find_elements()
是“最简单和最佳实践的方法(根据Selenium文档)”--你能将我链接到这些文档以供我自己学习吗?@C.Peck当你问问题时,我正在寻找它…:)。我用链接更新了我的答案。重要的一点是findElement不应用于查找不存在的元素,而是使用findElements(By)和断言零长度响应。
Nice。非常感谢。