Unable to login with python selenium error:NoSuchElementException error
Question: I have tried locating the submit button by id and xpath but none of them
worked and checked in the page source ,the id is same.I have no idea why this
is happening even though I am giving the correct Id or xpath  
  
**URL :** <https://moodle.niituniversity.in/moodle/login/index.php>  

    
    
    from pyvirtualdisplay import Display
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    display = Display(visible=0, size=(1024, 768))
    display.start()
    driver = webdriver.Firefox()
    #driver.set_preference("browser.startup.homepage_override.mstone", "ignore")
    driver.get("https://moodle.niituniversity.in/moodle/login/index.php")
    username = driver.find_element_by_name("username")
    username.clear()
    username.send_keys("User123")
    username.send_keys(Keys.RETURN)
    password = driver.find_element_by_name("password")
    password.clear()
    password.send_keys("pass123")
    password.send_keys(Keys.RETURN)
    password = driver.find_element_by_xpath(".//*[@id='loginbtn']").click()
    driver.get("https://moodle.niituniversity.in/moodle")
    assert "user" in driver.page_source
    driver.close()
    display.stop()
    

> .NoSuchElementException: Message: Unable to locate element:
> {"method":"xpath","selector":".//*[@id='loginbtn']"}


Answer: Might be possible this is timing issue, you should implement `WebDriverWait`
to wait until button present on page as below :-

    
    
    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
    
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "loginbtn")))
    element.click()
    

Full code :

    
    
    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.get("https://moodle.niituniversity.in/moodle/login/index.php")
    username = driver.find_element_by_name("username")
    username.clear()
    username.send_keys("User123")
    
    password = driver.find_element_by_name("password")
    password.clear()
    password.send_keys("pass123")
    
    button = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "loginbtn")))
    button.click()
    

