Search code examples
pythonseleniumxpathcss-selectorswebdriverwait

How to find a web element based upon it's tag name and attributes using Selenium and Python


I am trying to log into my Instagram account using Selenium. For that, I need to fill in my username and password into the login form.

The username input bar has the tag input and the name equal to username. Is there a way to retrieve this input bar using only the name attribute and the tag name? I know I can use the XPath and the class name, but I want to do this using the name attribute only.

I tried the code below but got an error.

Code:

username = driver.find_element(by = By.CSS_SELECTOR, value = "input[name = 'username']")
print(username.get_attribute("class"))

Output:

File "d:\Personal\CS\Bots\Instabot\msg.py", line 17, in <module>
    username = driver.find_element(by = By.CSS_SELECTOR, value = "input[name = 'username']")

Edit:

I tried the class name and the XPath too but they don't work either

XPath:

username = driver.find_element(by = By.XPATH, value = '//*[@id="loginForm"]/div/div[1]/div/label/input')
print(username.get_attribute("class"))

Class:

username = driver.find_element(by = By.CSS_SELECTOR, value = 'input._2hvTZ pexuQ zyHYP')
print(username.get_attribute("class"))

What am I doing wrong here?


Solution

  • You saw it right. The Phone number, username, or email <input> field has the name set as username.

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

    So to locate the element you can use either of the following Locator Strategies:

    • Using css_selector:

      element = driver.find_element(By.CSS_SELECTOR, "input[name='username']")
      
    • Using xpath:

      element = driver.find_element(By.XPATH, "//input[@name='username']")
      

    As the element is an interactive element ideally to locate the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

    • Using CSS_SELECTOR:

      element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='username']")))
      
    • Using XPATH:

      element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='username']")))
      
    • Note : You have to add the following imports :

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