In Selenium using Python facing error unable to locate element

  • from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    # create a new Firefox session
    driver = webdriver.Firefox()
    # Navigate to the application home page
    # get the search textbox
    search_field = driver.find_element_by_id("lst-ib")
    # enter search keyword and submit
    search_field.send_keys("Selenium WebDriver Interview questions")
    # get the list of elements which are displayed after the search
    # currently on result page using find_elements_by_class_name method
    lists= driver.find_elements_by_class_name("_Rm")
    # get the number of elements found
    print ("Found " + str(len(lists)) + " searches:")
    # iterate through each element and print the text that is
    # name of the search
    for listitem in lists:
       print (listitem.get_attribute("innerHTML"))
    # close the browser window

    Error message:

    Traceback (most recent call last):

      File "C:/Users/HP/Documents/", line 13, in <module>
        search_field = driver.find_element_by_id("lst-ib")
      File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\", line 360, in find_element_by_id
        return self.find_element(by=By.ID, value=id_)
      File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\", line 978, in find_element
        'value': value})['value']
      File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\", line 321, in execute
      File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\", line 242, in check_response
        raise exception_class(message, screen, stacktrace)
    selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="lst-ib"]

  • I believe you need to introduce Explicit Waits and use correct locators.

    For example:

    1. Change this line:

      search_field = driver.find_element_by_id("lst-ib")

      to this one:

      search_field = wait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//input[@name='q']")))
    2. Similarly:

      remove this line:

      lists= driver.find_elements_by_class_name("_Rm")

      and use the following instead:

      wait(driver, 10).until(lambda driver: len(driver.find_elements_by_class_name("r")) > 0)
      lists = driver.find_elements_by_class_name("r")

    You will need the following imports:

    from import By
    from import WebDriverWait as wait
    from import expected_conditions as EC

    More information:

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2