简体   繁体   中英

Can't find element by id - selenium

Despite use id I can't locate input element. I have tried CssSelector , Xpath , Id already. Why can't handle this element this way?

I have tried:

By id = By.Id("First name:input");
By xpath = By.Xpath("//*[@id=\\"First name:input\\"]");
By selector = By.CssSelector("#First\\ name\\:input");

I use explict wait to wait for input element.

Input Element:

 <div class="controlPaddingWrapper"> <label id="First name:">First name:</label> <input ng-attr-id="{{ c.Prompt+ 'input' }}" next-focus="" focus-if="true" class="k-textbox ng-pristine ng-empty ng-invalid ng-invalid-required ng-valid-pattern flow-required ng-touched" pattern=".+$" ng-model="c.Value" ng-class="{'flow-required': isRequired(c)}" required="" style="width: 100%;" ng-change="onChange(c)" id="First name:input" type="text"> </div> 

HTML The id Attribute

Try just: By id = By.Id("First name");

You can use:

By xpath = By.Xpath("//input[@id='First name:input']");
By selector = By.CssSelector("input[id='First name:input']");

As per the HTML you have shared to invoke Click() / SendKeys() on the desired element, as the element is an Angular element you need to indice WebDriverWait for the element to be clickable and you can use either of the following solutions:

  • CssSelector :

     new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("input.k-textbox.ng-pristine.ng-empty.ng-invalid.ng-invalid-required.ng-valid-pattern.flow-required.ng-touched[id*='First']"))).Click(); 
  • XPath :

     new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//input[@class='k-textbox ng-pristine ng-empty ng-invalid ng-invalid-required ng-valid-pattern flow-required ng-touched' and @id=\\"First name:input\\"]"))).Click(); 

Try this:

  1. Better change the ID's without space <label id="First_name">
  2. If you like to search by Id then try this: By.id("First_name")
  3. If you like to by XPath: By.Xpath("//*[@id='First_name']") or By.Xpath("//label[@id='First_name']") OR By.Xpath("//label[contains(text(), 'First name:')]") For Xpath reference you can find in here https://www.guru99.com/xpath-selenium.html

Sorry never been used By.CssSelector

 <div class="controlPaddingWrapper"> <label id="First name:">First name:</label> <input ng-attr-id="{{ c.Prompt+ 'input' }}" next-focus="" focus-if="true" class="k-textbox ng-pristine ng-empty ng-invalid ng-invalid-required ng-valid-pattern flow-required ng-touched" pattern=".+$" ng-model="c.Value" ng-class="{'flow-required': isRequired(c)}" required="" style="width: 100%;" ng-change="onChange(c)" id="First name:input" type="text"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM