【问题标题】:Selenium not able to select element by XPath based on attributesSelenium 无法根据属性通过 XPath 选择元素
【发布时间】:2021-03-14 20:28:43
【问题描述】:

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

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

任何关于我做错了什么的见解?

【问题讨论】:

  • 以 id 为目标会更好,因为它应该是唯一的。您似乎也在使用 alpha 版本...

标签: java selenium selenium-webdriver xpath webdriverwait


【解决方案1】:

你已经够近了。您已将 class 属性的值用作 mat-input-element,其中 class 的值是 mat-input-element mat-form-field-autofill-control cdk-text-field-autofill-monitored ng-dirty ng-valid ng-touched


解决方案

您可以使用以下任一Locator Strategies

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-18
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 2011-11-24
    • 2019-10-13
    相关资源
    最近更新 更多