首页 > 解决方案 > 我该如何做到,如果 XPATH 在网站上没有看到元素,它会跳过该行并移动到下一行?

问题描述

我该如何做到这一点,如果 XPATH 没有在页面上看到该元素,它会跳过该元素并移动到下一行?我的代码是:

1. driver.find_element_by_xpath('//img[@alt = "Black"]').click()

然后如果它没有找到第一个元素,它会跳过并尝试查找:

2. driver.find_element_by_xpath('//*[@id="add-remove-buttons"]/input').click()

我猜这与“如果显示___,单击,否则如果___单击”有关,尽管我不确定如何格式化。

标签: pythonseleniumxpath

解决方案


使用 try 和 catch 块并捕获 ElementNotFoundException 异常 Java:

try{
 //your code to find element
}
catch(ElementNotFoundException)
{
  //print element not found
}
// find another element and perform action

参考-https://www.w3schools.com/python/python_try_except.asp

Python:

 try:
  //your code
 except ElementNotFoundException:
   print("ELEMENT NOT fOUND")

推荐阅读