简体   繁体   English

硒(如果在屏幕上定位无法找到元素)

[英]Selenium if locate on screen unable to locate element

I'll keep this question simple: I have an if statement: 我将简单地回答这个问题:我有一个if语句:

if self.driver.find_element_by_xpath('//*[contains(@id, "mission_countdown")]'):

And i get this error: 我得到这个错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[contains(@id, "mission_countdown")]"}

Why do I get this? 为什么我得到这个? I mean its an if statement, IF its on screen 我的意思是它是一个if语句,如果它在屏幕上

Thanks for helping 感谢您的帮助

find_element_by_xpath can return find_element_by_xpath可以返回

  • WebElement (if any found) WebElement (如果找到)
  • NoSuchElementException (if not found) NoSuchElementException (如果未找到)

If you're searching for the output that can be evaluated as boolean to use in if / else block, try find_elements : 如果要搜索的输出可以评估为布尔值以在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')

The code below is an example. 下面的代码是一个示例。 It explicitly waits and moves to the object element you want to find. 它显式等待并移至要查找的对象元素。 Adding in the try will throw the except error message if it does not find the element 如果没有找到元素,则添加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")

I hope this helps 我希望这有帮助

Use try...catch block.If it is not their it will go to catch block.Let me know if this work for you. 使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM