我试图从这样的表格中筛选链接:
…
<table id="t">
<tr><td>Section 1</td></tr>
<tr><td>Some content</td></tr>
<tr><td>Some content</td></tr>
<tr><td>Some content</td></tr>
<tr><td>Some content</td></tr>
<tr><td><a href="some_link?for=one">View Report</a></td></tr>
<tr><td>Section 2</td></tr>
<tr><td>Some content</td></tr>
<tr><td>Some content</td></tr>
<tr><td>Some content</td></tr>
<tr><td>No report for section three</td></tr>
<tr><td>Some content</td></tr>
<tr><td>Section 3</td></tr>
<tr><td>Nothing for section four either.</td></tr>
<tr><td>Section 4</td></tr>
<tr><td>Some content</td></tr>
<tr><td>Some content</td></tr>
<tr><td><a href="some_link?for=four">View Report</a></td></tr>
<tr><td>Some content</td></tr>
</table>
…表中有三个部分,但它们是线性表示的,而不是分层表示的。每个部分可能有零个或一个链接,其文本为“查看报告”。
我可以使用什么XPath来选择与第n节对应的<a>元素(如果不存在这样的元素,则为空集合)?
作为第一次,我考虑过
//table[@id='t']/tr[td='Section %d']/following-sibling::tr/td/a['View Report'][1](其中%d是n的占位符)。但是,这将错误地选择n = 2的最后一个链接。
我也可以试试
//table[@id='t']/tr[td='Section %d']/following-sibling::tr[following-sibling::tr/td='Section %d']/td/a['View Report'][1]对于n和n + 1分别有两个%d占位符,但是对于最后一节,这是行不通的。此外,需要两个插值是不优雅的。是否有一个很好的解决方案来处理所有的案件?
发布于 2014-11-26 00:53:56
向后执行:找到前面的“任何部分”都是您正在寻找的“区段”的链接。
//a["View Report"][../../preceding-sibling::tr[td[contains(.,"Section")]][1][.="Section 3"]]/@href发布于 2014-11-26 00:05:53
如果没有对应于所讨论的部分的<a>元素,我不确定应该返回什么,但是如果<a>元素有一个值高于该节的前一节(n=2),则后面的<a>元素不会返回匹配:
//table[@id='t']/tr[td='Section 2']/following-sibling::tr/td[
not(./parent::tr/preceding-sibling::tr[
normalize-space(translate(td,'Section',''))>2])
]/a['View Report'][1](N):
//table[@id='t']/tr[td='Section n']/following-sibling::tr/td[
not(./parent::tr/preceding-sibling::tr[
normalize-space(translate(td,'Section',''))>n])
]/a['View Report'][1]https://stackoverflow.com/questions/27138705
复制相似问题