java - 两个属性的 xpath

标签 java html selenium xpath

我在处理一个元素上两个属性的 xpath 语法时遇到了问题。

这是我的代码:

WebElement dlFileBtn = driver.findElement(
   By.xpath("//*[contains(@href='/file/download/id/" + downloadID + "')]" 
          + "/@*[title()='Download file']"));

这是该元素的 HTML:

<a title="Download file" alt="Right-click to download. (Hold-click Mac.)" 
   target="dlfile" data-isimage="false" class="download" 
   href="/file/download/id/1169">Download file</a>

由于有两个具有相同 href 的按钮,我需要查询它们的 ID 和标题。感谢您的帮助!

最佳答案

contains() 函数的第一个谓词有问题。

  • contains() 接受两个参数。第一个参数是要测试的值,第二个是要搜索的值。它应该是 [contains(@href,'/file/download/id/"+ downloadID + "')]
  • 或者您可以使用 [@href='/file/download/id/"+ downloadID + "']
  • 测试整个值

XPath 的最后一部分有几个问题:/@*[title()='Download file']

  • /@* 不是对匹配的元素应用另一个谓词过滤器,而是选择所有匹配的元素属性,然后
  • [title()='Download file'] 是一个谓词过滤器,它尝试仅选择 title() 等于“下载”的属性文件”
  • 但是,没有 title() 节点选择器或函数来过滤这些属性

您可以使用多个谓词并将 XPath 的最后一部分调整为:

//*[@href='/file/download/id/" + downloadID + "'][@title='Download file']

您可以组合这些谓词过滤器并使用 andor 运算符测试同一谓词中的多个表达式。

//*[@href='/file/download/id/" + downloadID + "' and @title='Download file']

关于java - 两个属性的 xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52067186/

相关文章:

java - 如何避免大量 if-else 语句

java - 如何以格式化的方式存储和检索文本数据?

java - 在 Java 中的 App Engine 上复制 blobstore 实体的最佳方法是什么?

java - io.reactivex.exceptions.UndeliverableException 异常无法传递给消费者,因为它已经取消/处置

php - html 表单中的自动完成属性不起作用

javascript - 事件仅在触发两次时才会触发

css - 图像上有白色条纹?

linux - 使用 Jenkins 进行 Selenium 测试

Python Selenium - 按类和文本查找元素

selenium - 如何在 kotlin 中使用 div 角色和 aria-label 设置 xpath