selenium无法根据属性通过xpath选择元素

ymzxtsji  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(439)

我有一个输入/文本框,我需要找到和测试。通过检查浏览器上的元素,我发现元素如下:

<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="">

出于某种原因,我需要通过xpath找到这个元素(我使用的是java)。因此我试着:

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

获取错误:

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)

你知道我做错了什么吗?

cgvd09ve

cgvd09ve1#

你离得够近了。您已经将class属性的值用作 mat-input-element 其中类的值是 mat-input-element mat-form-field-autofill-control cdk-text-field-autofill-monitored ng-dirty ng-valid ng-touched ###解决方案
您可以使用以下任一定位器策略:
在lambda表达式中使用单个类atribute:

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

通过webdriverwait使用atribute类:

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

相关问题