![](/img/trans.png)
[英]Selenium Webdriver NoSuchElementException on python
[英]Selenium Webdriver NoSuchElementException
我将Selenium webdriver与Python结合使用来打印元素的内容,但是如果页面上不存在该元素,则会破坏我的代码并返回异常错误。
print (driver.find_element_by_id("TotalCost").text)
NoSuchElementException: Message: no such element: Unable to locate element
{"method":"id","selector":"TotalCost"}
我该如何解决此错误?
在try...except
块中捕获异常:
from selenium.common.exceptions import NoSuchElementException
try:
print(driver.find_element_by_id("TotalCost").text)
except NoSuchElementException:
print("Element not found") # or whatever you want to print, or nothing
为了清楚起见,也可以用这种方式做到这一点:
try:
elem = driver.find_element_by_id("TotalCost")
except NoSuchElementException:
pass
else:
print(elem.text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.