简体   繁体   中英

Selenium not able to select element by XPath based on attributes

I have an input/text box that I need to find and test with. By inspecting the element on the browser I found the element as:

    <input _ngcontent-tlw-c35="" autocomplete="off"
        class="mat-input-element mat-form-field-autofill-control cdk-text-field-autofill-monitored ng-dirty ng-valid ng-touched"
        matinput="" type="text"
        ng-reflect-required="true"
        ng-reflect-autocomplete="[object Object]"
        ng-reflect-autocomplete-attribute="off"
        ng-reflect-name="provider"
        ng-reflect-placeholder="Provider"
        ng-reflect-type="text" required="" id="mat-input-71" placeholder="Provider" aria-invalid="false" aria-required="true" aria-describedby="mat-hint-20 mat-hint-21" xpath="1" style="">

For a reason, I need to find this element by xpath ( I am using java). And hence I tried:

WebElement provider = super.wait(WAIT, INTERVAL).until(driver -> driver.findElement(By.xpath("//input[@class='mat-input-element' and @ng-reflect-placeholder='provider']")));

Getting error:

    Error Message: org.openqa.selenium.TimeoutException: Supplied function might have stalled
    Build info: version: '4.0.0-alpha-6', revision: '5f43a29cfc'
    System info: host: '38022f96913d', ip: '172.23.0.12', os.name: 'Linux', os.arch: 'amd64', os.version: '4.19.76-linuxkit', java.version: '11.0.9.1'
    Driver info: driver.version: unknown
    Stacktrace:
            org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:221)

Any insight on what am I doing wrong?

You were close enough. You have used the value of class attribute as mat-input-element where as the value of the class is mat-input-element mat-form-field-autofill-control cdk-text-field-autofill-monitored ng-dirty ng-valid ng-touched


Solution

You can use either of the following Locator Strategies :

  • Using a single class atribute in a lambda expression:

     WebElement provider = super.wait(WAIT, INTERVAL).until(driver -> driver.findElement(By.xpath("//input[contains(@class, 'mat-input-element') and @ng-reflect-placeholder='Provider']")));
  • Using the class atribute through WebDriverWait :

     WebElement provider = super.wait(WAIT, INTERVAL).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='mat-input-element mat-form-field-autofill-control cdk-text-field-autofill-monitored ng-dirty ng-valid ng-touched' and @ng-reflect-placeholder='Provider']")));

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