Search code examples
pythonpython-3.xseleniumselenium-webdrivergeckodriver

Selenium Python3 - Unable to find element by its name


The code of the HTML element is as follows:

<input aria-label="Phone number, username, or email" aria-required="true" autocapitalize="none" autocorrect="off" maxlength="75" name="username" type="text" class="_2hvTZ pexuQ zyHYP" value="">

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [name="username"]

I get the error above when I execute this code:

from selenium.webdriver import Firefox

class Efrit:

    #Initializing the bot
    def __init__(self, username, password):
        self.username = username    # it could also be e-mail or phone number
        self.password = password

#Credentials to log into Instagram:
    def log(self):
        driver = Firefox('/usr/local/bin')
        driver.get("https://www.instagram.com/")
        username_location = driver.find_element_by_name('username')
        password_location = driver.find_element_by_name('password')

bot = Efrit('test, 'test')
bot.log()

Solution

  • As said in the comments by JaSON, the login form is not in page source and it takes time to render. You have to use wait

    Explicit Wait

    from selenium.webdriver import Firefox
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException
    
        class Efrit:
            #Initializing the bot
            def __init__(self, username, password):
                self.username = username    # it could also be e-mail or phone number
                self.password = password
        
        #Credentials to log into Instagram:
            def log(self):
                driver = Firefox('/usr/local/bin')
                driver.get("https://www.instagram.com/")
                delay = 6 # seconds
                try:
                    username_location = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.NAME, 'username')))
                    password_location = driver.find_element_by_name('password')
                    print(username_location, password_location)
                except TimeoutException:
                    print("Loading took too much time!")
                driver.quit()
        
        bot = Efrit('test', 'test')
        bot.log()