[英]Selenium if locate on screen unable to locate element
我将简单地回答这个问题:我有一个if语句:
if self.driver.find_element_by_xpath('//*[contains(@id, "mission_countdown")]'):
我得到这个错误:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[contains(@id, "mission_countdown")]"}
为什么我得到这个? 我的意思是它是一个if语句,如果它在屏幕上
感谢您的帮助
find_element_by_xpath
可以返回
WebElement
(如果找到) NoSuchElementException
(如果未找到) 如果要搜索的输出可以评估为布尔值以在if
/ else
块中使用,请尝试find_elements
:
if self.driver.find_elements_by_xpath('//*[contains(@id, "mission_countdown")]'):
print('At least one element was found')
else:
print('No elements found')
下面的代码是一个示例。 它显式等待并移至要查找的对象元素。 如果没有找到元素,则添加try会抛出异常错误消息
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#--------
# all other code to begin scraping here
#--------
try:
if self.driver.find_element_by_xpath('//*[contains(@id, "mission_countdown")]'):
print("found this button")
elif:
print("not found trying new button ")
self.driver.find_element_by_xpath("xpath here")
except:
print("ERROR MESSAGE: NO ELEMENT FOUND")
我希望这有帮助
使用try...catch
块。如果不是,它将去捕获。让我知道这是否对您有用。
try:
if self.driver.find_element_by_xpath('//*[contains(@id, "mission_countdown")]'):
print('found')
except:
print('Not found')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.