gpt4 book ai didi

javascript - 如何获取特定标题之后的表格

转载 作者:行者123 更新时间:2023-11-28 00:54:59 26 4
gpt4 key购买 nike

我有一个 html在网站上有这样的结构,我正在编写一个脚本(js 在 Tampermonkey 上),它需要取回,它们在 “On way go” 下但那些在“在回来的路上”下的,所以我不知道我如何才能用聪明的方式实现它

我有代码要展示,因为我有这个想法,也许有一些 jquery 选择器可以帮助我,但我不知道所有的,并且没有在文档中找到

它只由 2 <h4> 组成然后它可以有 0 到 x 表,没有 id除了顶部的跨度外,表之间没有区别符号

<span id="idid">

<h4 class="spacer">On way go :</h4>
<table class="traders" cellpadding="1" cellspacing="1"> <!-- need this -->
<thead><!-- --></thead>
<tbody><!-- --></tbody>
</table>
<table class="traders" cellpadding="1" cellspacing="1"> <!-- need this -->
<thead><!-- --></thead>
<tbody><!-- --></tbody>
</table>

<h4 class="spacer">On way back</h4>
<table class="traders" cellpadding="1" cellspacing="1"> <!-- not this -->
<thead><!-- --></thead>
<tbody><!-- --></tbody>
</table>
<table class="traders" cellpadding="1" cellspacing="1"> <!-- not this -->
<thead><!-- --></thead>
<tbody><!-- --></tbody>
</table>
</span>

提示:不是我的网站,无法控制结构,我必须使用它

最佳答案

您可以使用 document.evaluate,使用 xpath 搜索文本以获取跨度,然后使用 nextElementSibling 获取表格:

let e = document.evaluate("//h4[contains(., 'On way go')]", document, null, XPathResult.ANY_TYPE, null);
let first = e.iterateNext();
let el = first.nextElementSibling;
while (el.tagName.toUpperCase() === 'TABLE') {
console.log(el);
el = el.nextElementSibling;
}
<span id="idid">

<h4 class="spacer">On way go :</h4>
<table class="traders" cellpadding="1" cellspacing="1"> <!-- need this -->
<thead><!-- --></thead>
<tbody><!-- --></tbody>
</table>
<table class="traders" cellpadding="1" cellspacing="1"> <!-- need this -->
<thead><!-- --></thead>
<tbody><!-- --></tbody>
</table>

<h4 class="spacer">On way back</h4>
<table class="traders" cellpadding="1" cellspacing="1"> <!-- not this -->
<thead><!-- --></thead>
<tbody><!-- --></tbody>
</table>
<table class="traders" cellpadding="1" cellspacing="1"> <!-- not this -->
<thead><!-- --></thead>
<tbody><!-- --></tbody>
</table>
</span>

如果您知道文本将完全是 On way go :,您还可以使用 "//h4[text()='On way go :']" 作为 xpath 表达式。

关于javascript - 如何获取特定标题之后的表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45382117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com