简体   繁体   English

Selenium 不能 select 元素由 XPath 基于属性

[英]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).出于某种原因,我需要通过 xpath 找到这个元素(我使用的是 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您已将class属性的值用作mat-input-element ,其中class的值是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:lambda表达式中使用单个class属性:

     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 :通过WebDriverWait使用class属性:

     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']")));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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