NoSuchElementException: Message: no such element: Unable to locate element when trying to find element within a iframe
Solution 1
To click()
on the desired element as the the desired element is within an <iframe>
so you have to:
- Induce WebDriverWait for the desired frame to be available and switch to it.
- Induce WebDriverWait for the desired element to be clickable.
-
You can use the following solution:
-
Code Block (using CSS_SELECTOR):
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#codefile_iframe"))) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#ok[value='OK'][onclick^='loginui']"))).click()
-
Code Block (using XPATH):
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='codefile_iframe']"))) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='ok' and @value='OK'][starts-with(@onclick,'loginui')]"))).click()
-
Here you can find a relevant discussion on Ways to deal with #document under iframe
Solution 2
You will need to switch to iframe before interacting with elements inside of it:
iframe = driver.find_element_by_id("codefile_iframe")
driver.switch_to.frame(iframe)
And then continue with the wait and click.
Related videos on Youtube
asguldbrandsen
Updated on May 25, 2022Comments
-
asguldbrandsen almost 2 years
I am trying to automate a Google Chrome session in Python using Selenium. Until now, I have been using an extension to get the xpath, which works OK. But now, I encounter an error when using the xpath I have located:
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="ok"]"} (Session info: chrome=71.0.3578.98) (Driver info: chromedriver=2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387),platform=Windows NT 6.3.9600 x86_64)
The line that returns an error looks like this:
browser.find_element_by_xpath('//*[@id="ok"]').click()
Unfortunately, the button I need to click is pretty deep within a webpage and requires a certain plugin, which makes it hard for you to replicate the flow of my program. Therefore, I have uploaded an image of the source code of the webpage (The blue line is the button I would like to click):
Could you provide some help on how to correct the selenium selector, so that I will be able to click the element?