Java 如何使用 xpath 获取 HTML5 数据属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21702007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:09:48  来源:igfitidea点击:

How to get HTML5 data attribute using xpath?

javarubyxpathselenium-webdrivercapybara

提问by Bala

How do I get the first table (table1) using xpath for Webdriver?

如何使用 xpath for Webdriver 获取第一个表 (table1)?

<span id="dynamically generated id" data-id="table1">
  <table>
  ...
  </table>
</span>

<span id="dynamically generated id" data-id="table2">
  <table>
  ...
  </table>
</span>

I am able to get all data-idelements but I want to filter within it for text table1to get the exact element.

我能够获取所有data-id元素,但我想在其中过滤文本table1以获取确切元素。

This did not work!

这没有用!

driver.findElement(By.xpath("//@*[starts-with(name(),'data-id') [contains(text(),'table1')]]")); 

采纳答案by Bala

Answering my own question...This appears to get the exact element.

回答我自己的问题......这似乎得到了确切的元素。

driver.findElement(By.xpath("//*[@data-id='table1']"))

回答by Moritz Petersen

You get the table like this:

你得到这样的表:

//span[@data-id='table1']/table

Select the data-idattribute and get the child element of name table.

选择data-id属性并获取 name 的子元素table

回答by Uri Agassi

Try (built this be combining xpath: find a node that has a given attribute whose value contains a stringand Getting attribute using XPath)

尝试(构建这个结合xpath:找到一个具有给定属性的节点,其值包含一个字符串使用 XPath 获取属性

driver.findElement(By.xpath("//*[contains(@data-id, 'table1')]/@data-id"));

回答by Adam Bilinski

I think you can also use the cssSelector

我想你也可以使用 cssSelector

driver.findElement(By.cssSelector("[data-id='table1']"));