我在下面的HTML代码中有一个表:
<table style="padding: 0px; border-collapse: collapse;">
<tr>
<td><h3>My Regional Financial Office</h3></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><h3>My Address</h3></td>
</tr>
<tr>
<td>000 Test Ave S Ste 000</td>
</tr>
<tr>
<td>Golden Valley, MN 00000</td>
</tr>
<tr>
<td><a href="javascript:submitForm('0000','0000000');">Get Directions</a></td>
</tr>
<tr>
<td> </td>
</tr>
</table>
如何在包含文本“我的地址?”的tablerow之后获取下两个<tr>
标签的内部文本。
您可以使用以下XPath:
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var tdOfInterests =
htmlDoc.DocumentNode
.SelectNodes("//tr[td/h3[.='My Address']]/following-sibling::tr[position() <= 2]/td");
foreach (HtmlNode td in tdOfInterests)
{
//given html input in question following code will print following 2 lines:
//000 Test Ave S Ste 000
//Golden Valley, MN 00000
Console.WriteLine(td.InnerText);
}
上面XPath的关键是使用following-sibling
与position()
过滤器。
更新:
关于这个答案中使用的XPath的一点解释:
//tr[td/h3[.='My Address']]
上面的部分选择<tr>
元素:
<h3>
元素的child <td>
元素,其值等于“我的地址” /following-sibling::tr[position() <= 2]
下一个部分选择以下<tr>
与位置元素<= 2从当前<tr>
元素 (一个由上面的XPath部分选择)
/td
最后一部分从当前<tr>
元素中选择child <td>
<tr>
元素