Selenium无法根据属性通过XPath选择元素



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

<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)

你知道我做错了什么吗?

你已经足够接近了。您已将class属性的值用作mat-input-element,其中class的值为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:使用属性

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

最新更新