Home > Software design >  Python/Selenium Identifying an element issue
Python/Selenium Identifying an element issue

Time:12-21

im trying to log in with python into webpage, but for some reason i cant get correct login element no matter what i try, because im noob and this is my first attempt.

This is supposed to be the element from webpage:

<label >Username</label>
<input type="text" formcontrolname="username" >

I have tried search by label without success:

username = browser.find_element_by_xpath("//label[contains(text(),'Username')]")

I have tried search by class:

username = browser.find_element_by_xpath('//input[@]')

I have tried search with CssSelector:

username = browser.find_element_by_css_selector("input[formcontrolname='Username']")

I have even tried full road:

username = browser.find_element_by_xpath("/html/body/app/div[@class='app-container']/ng-component/div[@class='container']/div[@class='row']/div[@class='col']/div[@class='card']/ng-component/div[@class='card-body']/form[@class='ng-pristine ng-invalid ng-touched']/div[@class='form-group'][1]/input[@class='form-control ng-pristine ng-invalid ng-touched']")

I don't know what i'm doing wrong, please help

CodePudding user response:

To locate the clickable 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:

    username = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[formcontrolname='username']"))).click()
    
  • Using XPATH:

    username = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@formcontrolname='username']"))).click()
    
  • 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
    

CodePudding user response:

There are several possible issues:

  1. You may be missing a wait / delay to let the page loaded before you try accessing the elements.
  2. The element may be located inside an iframe, so you will have to switch to that iframe in order to access the elements inside it.
  3. The locator may be not unique.
    To give more clear answer we need to see the we page you are working with and all your relevant code
  • Related