Search code examples
pythonselenium-chromedriverelement

Element cannot be found using python Selenium


I have been trying to automate a task. It's pretty simple. My aim is to get Selenium to put numbers in the search bar named "CAS number" (on the right side, the bottom), and press enter for submission. Below is my code

try:
    driver.get('https://www.efsa.europa.eu/en/microstrategy/openfoodtox')
except Exception:
    pass

#this one is for accepting cookies
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'ppms_cm_agree-to-all')))
element.click()

#this one is for locating the search bar for CAS number
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="mstr688"]/div[1]')))

element.click()
time.sleep(1)
element.send_keys(cas)
element.send_keys(Keys.ENTER)

Coding stops at a point where it's supposed to detect the search bar for CAS number. I think it has a problem with locating the element for the search bar. This search bar is different from other search bars I encounter on other websites because it's not right-clickable until it's first enabled by a left-click. Below is a screenshot of the highlighted element of the search bar.

enter image description here

I couldn't think of trying any other way other than XPATH because it seems like other locator info such as ID or NAME is not available. Waiting until it's fully loaded did not work.


Solution

  • It was because Cas Search bar is part of iframe, which selenium cannot acess directly without switching to it enter image description here

    In Below code before finding for search bar element, i am switching to the iframe it resides in and then Clicking on the displayed text and then entering the value try: driver.get('https://www.efsa.europa.eu/en/microstrategy/openfoodtox') except Exception: pass

    # this one is for accepting cookies
    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'ppms_cm_agree-to-all')))
    element.click()
    
    # Switch to iframe
    
    iframe = driver.find_element(By.XPATH, "//iframe[@class=\"microstrategy-iframe\"]")
    driver.switch_to.frame(iframe)
    
    # Clicking on text Search CAS number which will then show the input for Search Otherwise we will get not interactable exception
    element = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.XPATH, '//div[text()="Search CAS number"]//..')))
    element.click()
    
    time.sleep(1)
    # enter the value in search box input
    inputBox = driver.find_element(By.XPATH, '//div[text()="Search CAS number"]//..//preceding-sibling::input')
    inputBox.send_keys("cas" + Keys.ENTER)