硒找不到元素

时间:2020-02-21 15:21:20

标签: python html selenium-webdriver selenium-chromedriver

我正在尝试检索要单击的元素。这是带有Selenium in Python的网站的开幕:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--dns-prefetch-disable')
driver = webdriver.Chrome("./chromedriver", options=chrome_options)
website = "https://www.agronet.gov.co/estadistica/Paginas/home.aspx?cod=4"
driver.get(website)  # loads the page

然后,我寻找我感兴趣的元素:

driver.find_element_by_xpath('//*[@id="cmbDepartamentos"]')

会引发NoSuchElementException错误。当查看html源(driver.page_source)时,实际上“ cmbDepartamentos”不存在!并且我尝试查找的下拉菜单的文本为“ Departamentos:”也不存在。我该如何处理?

1 个答案:

答案 0 :(得分:1)

这应该有效:

iframe=driver.find_element_by_xpath('//div[@class="iframe"]//iframe')
driver.switch_to.frame(iframe)
driver.find_element_by_xpath('//*[@id="cmbDepartamentos"]').click()

注释:

  • 发生NoSuchElementException错误的原因是该元素是 iframe中。除非您将驱动程序切换到该iframe,否则, 标识将不起作用。
  • 在“开发工具”面板中,按
  • CTRL + F,然后搜索xpath 在脚本中定义变量始终是排除问题的好方法 您的xpath定义,作为NoSuchElementException错误的原因(在您的情况下,xpath是正确的)
  • 您可能希望在尝试查找“部门”字段之前考虑添加WebdriverWait来完全加载搜索区域/ iframe