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

前端 未结 7 2249
长发绾君心
长发绾君心 2020-12-02 14:00

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

相关标签:
7条回答
  • 2020-12-02 14:01

    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()
    
    0 讨论(0)
  • 2020-12-02 14:01

    it just means the function is executing before button can be clicked. Example solution:

    from selenium import sleep
    # load the page first and then pause
    sleep(3)
    # pauses executing the next line for 3 seconds
    
    0 讨论(0)
  • 2020-12-02 14:04

    this worked for me (the try/finally didn't, kept hitting the finally/browser.close())

    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('mywebsite.com')
    
    username = None
    while(username == None):
        username = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "username"))
        )
    username.send_keys('myusername@email.com')
    
    0 讨论(0)
  • 2020-12-02 14:16

    You can also use below as an alternative to the above two solutions:

    import time
    time.sleep(30) 
    
    0 讨论(0)
  • 2020-12-02 14:20

    Also for some, it may be due to opening the new tabs when clicking the button(not in this question particularly). Then you can switch tabs by command.

    driver.switch_to.window(driver.window_handles[1]) #for switching to second tab
    
    0 讨论(0)
  • 2020-12-02 14:27

    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
    
    0 讨论(0)
提交回复
热议问题