首页 > 解决方案 > 如何检查 Selenium (Python) 中是否存在元素?

问题描述

您好我正在尝试从 HTML 中选择名称“Saleem”。它在一张桌子里面,但我不知道这是否相关。名称可能并不总是存在,因此如果名称包含在表中,我正在尝试找到一种选择元素的方法。例如,“Liam”在搜索时不会出现,但“saleem”会出现。如何单击搜索 saleem 时出现的链接?出于某种原因,Selenium 无法使用我在下面编写的代码找到元素。

这是网站(我只是将 Saleem 放在名称类别中并搜索): https ://sanctionssearch.ofac.treas.gov/default.aspx

我尝试了下面的代码,但不幸的是不起作用。

driver.find_element_by_id("btnDetails").click()

 <a> id="btnDetails" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContent$gvSearchResults$ctl02$btnDetails&quot;, &quot;&quot;, false, &quot;&quot;, &quot;Details.aspx?id=5839&quot;, false, true))" style="color:Blue">AL-IFRI, Saleem </a>

任何帮助表示赞赏!

标签: pythonseleniumselenium-chromedriver

解决方案


是的,你可以在里面使用它try..except

from selenium.common.exceptions import NoSuchElementException

# YOUR CODE 
        
try:
  webdriver.find_element_by_id('btnDetails')
except NoSuchElementException:
  # Element does not exist
else:
  # Element exists

推荐阅读