如何通过Java使用Selenium通过href属性查找元素

时间:2019-11-14 12:56:20

标签: java selenium xpath webdriverwait expected-condition

我正在尝试使用href找到以下元素。

<a class="compliance-documents-link-text" target="_blank" href="api/Document/GetDocumentByType/25194300-f620-4cc9-a375-419b1ebfe729/1">
<span>Acceptance Criteria</span>
</a>

我必须使用href="api/Document/GetDocumentByType/25194300-f620-4cc9-a375-419b1ebfe729/1",因为我需要区分所有都有验收标准但文档链接不同的产品。

我目前有:

wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[@href ='api/Document/GetDocumentByType/8d844ee3-b9cc-4d5c-87ee-8363bf46164a/1']")));

,但是找不到元素。

2 个答案:

答案 0 :(得分:1)

您的XPATH不正确。

在您的代码中,href值的末尾为“ 419b1ebfe729 / 14”,而在您所提及的末尾为“ 419b1ebfe729 / 1”。

答案 1 :(得分:-1)

所需元素是动态元素,因此要定位click()并将其放置在elementToBeClickable()的元素上,可以使用new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='compliance-documents-link-text' and starts-with(@href, 'api/Document/GetDocumentByType/')]//span[text()='Acceptance Criteria']"))).click(); WebDriverWait ,您可以使用以下任一{ {3}}:

  • xpath 1:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='compliance-documents-link-text' and starts-with(@href, 'api/Document/GetDocumentByType/')][./span[text()='Acceptance Criteria']]"))).click();
    
  • xpath 2:

    <div class="paperSheet">
       <div class="paperSheet__message">
          <p> Title </p>
          <p> Text </p>
       </div>
       <div class="paperSheet__message">
          <p> Title </p>
          <p> Text </p>
       </div>
    </div>