如何检查python selenium中是否存在extgen元素

2024-05-02 00:13:54 发布

您现在位置:Python中文网/ 问答频道 /正文

 def conformation():
  try:
    conf_btn= driver.find_element(By.ID, "ext-gen1315")
    #Error_alert
    err_alert=driver.find_element_by_xpath("//a[@class='x-btn x-unselectable rp-btn-shadow rp-important-btn x-box-item x-toolbar-item x-btn-default-small x-noicon x-btn-noicon x-btn-default-small-noicon' and @id='button-1016']")
    err_alert.click()
    print("success")
    return 0   
  except NoSuchElementException:
    print ("conformation div element not found")
    return 1

在这个函数中,我需要检查这个ext-gen1315div元素是否存在,然后单击err_alert按钮,否则返回1

我总是只得到NoSuchElementException。在运行此命令时,我可以在浏览器的inspect元素中看到此元素。我不知道我在哪里犯了错误

引发异常类(消息、屏幕、堆栈跟踪) selenium.common.exceptions.NoSuchElementException:Message:没有这样的元素:找不到元素:{“方法”:“xpath”,“选择器”:“//a[@class='x-btn x-unselectable rp-btn shadow rp重要btn x-box-item x-toolbar-item x-btn-default-small x-noicon x-btn-default-small-noicon'和@id='button-1016']}

但我可以在检查时看到元素 enter image description here


Tags: default元素driveralertelementfinditemext
3条回答

不确定这是什么类型的警报框,但如果它是标准警报,则有一种驱动程序方法更优雅。如果这是模态,则可能不起作用

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

try:
    WebDriverWait(browser, 3).until(EC.alert_is_present())
    driver.switch_to_alert.accept()
    return 0
except TimeoutException:
    return 1

这应该做到:

conf_btn= driver.find_element(By.ID, "ext-gen1315")
if conf_btn:
    err_alert=driver.find_element_by_xpath("//a[@class='x-btn x-unselectable rp-btn-shadow rp-important-btn x-box-item x-toolbar-item x-btn-default-small x-noicon x-btn-noicon x-btn-default-small-noicon' and @id='button-1016']")
    err_alert.click()
    print("success")
    return 0 
else: 
    return 1

我宁愿使用find_elements,这样您就不会产生不必要的期望

def conformation():
    if (len(driver.find_elements_by_xpath("//a[@class='x-btn x-unselectable rp-btn-shadow rp-important-btn x-box-item x-toolbar-item x-btn-default-small x-noicon x-btn-noicon x-btn-default-small-noicon' and @id='button-1016']"))>0):
        driver.find_element_by_xpath("//a[@class='x-btn x-unselectable rp-btn-shadow rp-important-btn x-box-item x-toolbar-item x-btn-default-small x-noicon x-btn-noicon x-btn-default-small-noicon' and @id='button-1016']").click()
        print("success")
        return 0
    else:
        print("conformation div element not found")
        return 1

相关问题 更多 >