【问题标题】:Selenium if locate on screen unable to locate elementSelenium 如果在屏幕上定位无法定位元素
【发布时间】:2019-02-28 20:02:50
【问题描述】:

我会让这个问题保持简单: 我有一个 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 语句,如果它在屏幕上

感谢您的帮助

【问题讨论】:

  • 如果它在屏幕上执行您定义的任何内容,如果不是,您使用的代码是什么?你是否定义了一个 else 子句来检查它是否不在屏幕上?
  • 如果它不在屏幕上,他只需要打印 hi,不,我没有 else 子句来检查它是否不在屏幕上
  • 也许你应该添加一个 else 子句,因为如果它不在屏幕上它会崩溃,因为没有条件检查
  • 我现在添加了一个不在屏幕上的 elif,但它仍然停留在第一个 if 上,说我无法定位
  • 如果它在屏幕上一切正常,但如果它不在屏幕上则不行

标签: python selenium if-statement error-handling


【解决方案1】:

下面的代码是一个例子。 它显式等待并移动到您要查找的对象元素。如果找不到元素,添加try会抛出except错误消息

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: except 和 if elif。我已经编辑了
  • 这也不起作用,但我有解决方案...我只需要写 find_element S 谢谢
【解决方案2】:

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')

【讨论】:

  • 我真的不知道为什么,因为它在屏幕上只有一个元素,但这是可行的:)
  • @LaurenzZ 不像 find_element_by_xpath find_elements_by_xpath 返回 WebElements 列表或空列表 []。两种情况下的输出都可以评估为布尔值:非空列表始终为True,空列表始终为False,因此您可以在if/else中使用它 - 它永远不会导致异常
  • @LaurenzZ 如果你不明白这一点,你应该再读几遍,直到你明白为止。这是非常重要的信息,如果您打算继续编写 Selenium 代码,将对您很有用。
【解决方案3】:

使用try...catch 块。如果不是他们的,它将去捕获块。如果这对你有用,请告诉我。

try:
    if self.driver.find_element_by_xpath('//*[contains(@id, "mission_countdown")]'):
        print('found')
except:
    print('Not found')

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 2021-06-21
    • 1970-01-01
    • 2017-08-06
    • 2017-11-27
    • 2018-07-06
    相关资源
    最近更新 更多