Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element:

I'm trying to automatically generate lots of users on the webpage kahoot.it using selenium to make them appear in front of the class, however, I get this error message when trying to access the inputSession item (where you write the gameID to enter the game)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.kahoot.it")

gameID = driver.find_element_by_id("inputSession")
username = driver.find_element_by_id("username")

gameID.send_keys("53384")

This is the error:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element:
{"method":"id","selector":"inputSession"}
like image 671
Morten Stulen Avatar asked Nov 24 '14 19:11

Morten Stulen


People also ask

What is NoSuchElementException in Selenium?

NoSuchElementException occurs, when the locators (i.e. id / xpath/ css selectors) is unable to find the web element on the web page. The reasons for this could be : Incorrect Locator. Web element not available on web page. In order to avoid this exception, we can use Fluent Wait.

How do you handle an element not visible exception?

First Solution: Try to write unique XPATH that matches with a single element only. Second Solution: Use Explicit wait feature of Selenium and wait till the element is not visible. Once it is visible then you can perform your operations.


2 Answers

Looks like it takes time to load the webpage, and hence the detection of webelement wasn't happening. You can either use @shri's code above or just add these two statements just below the code driver = webdriver.Firefox():

driver.maximize_window() # For maximizing window
driver.implicitly_wait(20) # gives an implicit wait for 20 seconds
like image 125
Subh Avatar answered Oct 12 '22 14:10

Subh


Could be a race condition where the find element is executing before it is present on the page. Take a look at the wait timeout documentation. Here is an example from the docs

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()
like image 27
shri046 Avatar answered Oct 12 '22 16:10

shri046