0

I am doing this:

WebElement userName = driver.findElement(By.id("username"));

but I get:

Unable to locate element: #username

My DOM looks like this:

<input type="text" name="username" id="username" class="u-leader-m10"
required="required" tabindex="1">

From the looks of it, everything is alright. So, what are some areas to investigate this failure? Happy to provide more info. I just don't know what can be relevant.

Edit: I've tried 'name' instead of 'id' and it's working - still confused!

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
DraxDomax
  • 1,008
  • 1
  • 9
  • 28
  • 1) check if you are trying to get the element before page loading is completed (if yes then use WebDriverWait with ExpectedConditions) 2) check if the username is present in the iframe (if yes, then make sure to switch to frame before trying to access the element) – supputuri Sep 11 '19 at 03:39

2 Answers2

0

Try with the below one

WebElement userName = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("username")));
Ashok kumar Ganesan
  • 1,098
  • 5
  • 20
  • 48
Quoc Cao
  • 11
  • 2
0

Apparently, I don't see any issue with your code block using the id attribute, however the optimum strategy to locate elements within the HTML DOM will depend a lot on the type of the DOM Tree and your desired actions on the elements.

Having said that, it seems the element is a <input> element and moving forward either you would invoke click() or sendKeys() and to achieve that you have to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

  • cssSelector:

    WebElement userName = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input#username[name='username']")));
    
  • xpath:

    WebElement userName = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='username' and @name='username']")));
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352