想象下面HTML文件的一部分:
<div class='span1 league'>
<div class='league-gold-1 leagues size-64'></div>
</div>
<div class='span4 stats'>
<div class='points'>
<span class="gold">491</span>
points
(<span class="gold">391</span> away for region #1)
</div>
<div class='games'>
Won <span class="text-success">37</span>,
lost <span class="text-error">51</span>,
ratio <span>42.05</span>%
</div>
<div class='race'>
Favorite Race:
<div class='race-terran races size-16'></div>
<span>Terran</span>
</div>
</div>
在这种情况下,我需要获得37和51的赢和输的游戏数量。也是要点(在这种情况下是491)。我一直在尝试使用html敏捷包但到目前为止还没有成功。如果你现在解决这个问题,请告诉我!
答案 0 :(得分:1)
var doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(fname);
var won = doc.DocumentNode.SelectSingleNode("//div[@class='games']/*[@class='text-success']").InnerText;
var lost = doc.DocumentNode.SelectSingleNode("//div[@class='games']/*[@class='text-error']").InnerText;
var points = doc.DocumentNode.SelectSingleNode("//div[@class='points']/*[@class='gold']").InnerText;
您也可以使用Linq而不是XPath
var won = doc.DocumentNode.Descendants("span")
.First(s=>s.Attributes.Any(a=>a.Value=="text-success"))
.InnerText;
答案 1 :(得分:0)
作为一种解决方法,您可以尝试使用正则表达式
Match m = Regex.Match(htmlstring, "<span class=\"text-success\">([0-9]+?)</span>.*?<span class=\"text-error\">([0-9]+?)</span>", RegexOptions.Singleline);
string won = m.Result("$1");
string loss = m.Result("$2");