如何找到非唯一 id/class 的 div,其中包含带有特定文本的 div,然后获取该 <td> 和 <tr> 下的所有标签 div

How to locate a div with non unique id/class, which contains a div with a certain text and then fetch all the <td> and <tr> tags under that div

所以我有 HTML 类似的东西。

<div class="generic classname" id="generic ID name" >  // div1
<div class="presentation" id="body presentation">      // div2
<font>unique text</font>
<div class= "generic classname" id="generic ID name""> //div3
// under this div I have the table entry.
// multiple <td> and <tr>
</div>
</div>
</div>

我的工作是匹配div no 2中的“唯一文本”,所以我可以找到元素div number 1,然后获取[=中的所有table 27=] 没有 3

问题是我不确定如何找到没有唯一 class 名称或 ID 名称 的 div。我不能使用完整的 XPath,因为 table 变化并且 divs 随机变化。

我会用js搜索或获取“唯一文本”的标签

<script>
  // get the element
  let elem = document.getElementsByName('font');
</script>

https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp

使用下面的xpath参考div 2找到唯一的文本,然后在div.[=13中找到div和table =]

//div[./font[text()='unique text']]/div[1]/table

如果你所有的 div 都像你说的那样嵌套并且你的目标是在 div3 中获得 table,你不需要获得父级。

这是一个选项:

//font[text()='unique text']/following-sibling::div

此 xpath 找到带有您的唯一文本的 font 然后它是兄弟(同父)div

这个 xpath 标识符是另一个选项:

//font[text()='unique text']/parent::*/div

此 xpath 使用您的唯一文本找到 font,然后获取它的 *(任何)父级,然后在其中获取相关的 div。

如果你想要“div1”,你可以把父坐标轴再做一次向上。

在开发工具中看起来像这样:

这是基于您的 html 长相:

<div class="generic classname" id="generic ID name" >
    <div class="presentation" id="body presentation">
        <font>unique text</font>
        <div class="generic classname" id="generic ID name""> 
            // under this div I have the table entry.
            // multiple <td> and <tr>
        </div>
    </div>
</div>

不同的 HTML 需要不同的 xpath,所以请说明是否需要更新。

您还有一个选择:

//div[font='unique text']/div

根据 HTML:

<div class="generic classname" id="generic ID name" >  // div1
    <div class="presentation" id="body presentation">      // div2
        <font>unique text</font>
        <div class= "generic classname" id="generic ID name"> //div3
            // under this div I have the table entry.
            // multiple <td> and <tr>
        </div>
    </div>
</div>

由于您的用例不依赖于任何 <div1> 属性,因此您可以轻松避免考虑 <div1>.


解决方案

要找到第三个 <div>,您有以下四种方法:

  • 使用文本 unique text<div> attributes:

    //font[text()='unique text']//following::div[@class='generic classname' and @id='generic ID name']
    
  • 使用文本unique text索引:

    //font[text()='unique text']//following::div[1]
    
  • 使用 <div2>,它有一个子 <font> 标签,文本为 unique text<div> attributes:

    //div[./font[text()='unique text']]//following-sibling::div[@class='generic classname' and @id='generic ID name']
    
  • 使用 <div2>,它有一个子 <font> 标签,文本为 unique textindex

    //div[./font[text()='unique text']]//following-sibling::div[1]