获取第二个span标记的内容

时间:2015-12-12 22:30:47

标签: c# html-agility-pack

我正在攻击html敏捷包并且无法找到正确的方法来解决这个问题。 例如: 我想获得第二个span标记的内容:

htmlDoc.DocumentNode.SelectSingleNode("//div[@style='color:#000000; padding: 10px;']/table/tr[1]/td[1]/span[2]").InnerText;

这是我想用HTML AGILITY PACK解析的html文件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body onload="oload()" onunload="Unload()">

<div id="content">
<table width="100%">
<tr>
    <td width="48%" valign="top">
<fieldset style="border:1px solid #ccc;color:#ccc;margin:0;padding:0;">
<legend style="color:#ccc;margin:0 0 0 10px;padding:0 3px;">Profile Information</legend>
<div style="color:#000000; padding: 10px;">
<br />
Name Surname:<br />
<span style="font-size:18px;">John Doe</span>
<br /><br /><br />
Address:<br />
<span style="font-size:18px;">706 test<br>NY 14013</span>
<br /><br /><br />
</div>
</fieldset>
<br />
</td>
    <td width="52%" align="right" valign="top">
</td>
</tr>
</table>
    </div>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

根据发布的HTML代码段,包含目标span的所有span[2]元素都直接位于div内,因此正确的XPath就是:

//div[@style='color:#000000; padding: 10px;']/span[2]

在线演示链接:https://dotnetfiddle.net/mRfLEQ

输出

706 testNY 14013

答案 1 :(得分:0)

试试这个:

-[appController:evaluateAppJavaScriptInContext:]

基本上,using System; using System.Collections.Generic; using System.Linq; using System.Text; using HtmlAgilityPack; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { String html = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd""> <html xmlns=""http://www.w3.org/1999/xhtml""> <head> </head> <body onload=""oload()"" onunload=""Unload()""> <div id=""content""> <table width=""100%""> <tr> <td width=""48%"" valign=""top""> <fieldset style=""border:1px solid #ccc;color:#ccc;margin:0;padding:0;""> <legend style=""color:#ccc;margin:0 0 0 10px;padding:0 3px;"">Profile Information</legend> <div style=""color:#000000; padding: 10px;""> <br /> Name Surname:<br /> <span style=""font-size:18px;"">John Doe</span> <br /><br /><br /> Address:<br /> <span style=""font-size:18px;"">706 test<br>NY 14013</span> <br /><br /><br /> </div> </fieldset> <br /> </td> <td width=""52%"" align=""right"" valign=""top""> </td> </tr> </table> </div> </body> </html>"; var doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(html); var spans = doc.DocumentNode.SelectNodes("//span"); Console.WriteLine(spans[1].InnerText); } } } 将提供所有doc.DocumentNode.SelectNodes("//span");节点并使用index来显示第二个innertext

相关问题