硒没有接触元素异常,但元素存在

2024-09-28 22:26:37 发布

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

我有这个密码

driver.implicitly_wait(300) #I have tried different timers
driver.find_element_by_xpath("(//button[@aria-pressed='false'])[1]").click()

但是我得到了这个错误

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"(//button[@aria-pressed='false'])[1]"}

然而,这存在于我的HTML中

<div class="webix_el_box" style="width:90px; height:26px">
<button aria-pressed="false" type="button" class="webix_img_btn" style="line-height:22px;">
<span class="webix_icon_btn fa-lock red" style="max-width:22px;">
</span> Read Only
</button>
</div>

我还尝试使用xpath

//button[@class='webix_img_btn']//child::span[@class='webix_icon_btn fa-lock red']

这两种xpath在Google Chrome中都运行良好 在网站中,我可以使用Ctrl+F和“只读”找到按钮,我可以在Selenium中使用它吗

编辑:由于Selenium Driver is one page behind ajax call after large json data download而无法工作


Tags: divfalsestyledriverbuttonelementwidthxpath
2条回答

要单击文本为只读的元素,必须为element_to_be_clickable()归纳WebDriverWait,并且可以使用以下Locator Strategies之一:

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.webix_el_box > button.webix_img_btn"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='webix_el_box']/button[@class='webix_img_btn' and contains(., 'Read Only')]"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

参考资料

你可以在以下网站上找到关于NoSuchElementException的一些相关讨论:

试着去做

driver.implicitly_wait(300)
driver.find_element_by_xpath("//button[@aria-pressed='false']").click()


这将单击满足要求的第一个元素

相关问题 更多 >