我在一个网站上有这样一个html
结构,我正在写一个脚本(js
在Tampermonkey上),它需要返回“on way go”下面的表,但是“on way back”下面的表,所以我不知道如何用一种聪明的方法来实现它
我有代码要显示,因为我有这个想法,也许有一些jquery选择器可以帮助我,因为我不知道所有的,也没有在文档中找到
它只由2个cc组成,然后可以在0到x表之间,除了顶部的跨度和表之间没有区分符号外,不存在<h4>
。
<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表达式。