Vladimir Vargas
Vladimir Vargas

Reputation: 1834

Selenium not finding an element

I am trying to retrieve an element that I would like to click on. Here's the opening of the website with 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

Then, I look for the element I'm interested in:

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

which raises a NoSuchElementException error. When looking at the html source (driver.page_source), indeed "cmbDepartamentos" does not exist! and the text of the dropdown menu I am trying to locate which is "Departamentos:" does not exist either. How can I deal with this?

Upvotes: 0

Views: 488

Answers (1)

0buz
0buz

Reputation: 3503

This should work:

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

Notes:

  • The reason for NoSuchElementException error is that the element is inside an iframe. Unless you switch your driver to that iframe, the identification will not work.
  • CTRL + F in the Dev Tools panel, then search for the xpath you defined in your script is always a good way to rule out issues with your xpath definition, as cause for NoSuchElementException error (and in your case, the xpath is correct)
  • You might want to consider adding a WebdriverWait for a complete load of the search area/iframe before attempting to find the "Departamentos" field

Upvotes: 1

Related Questions