本文介绍了C#解析HTML使用XPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我试图分析出证券交易所信息从一个HTML文档白衣一段简单的C#。问题是,我不能让我的头周围的语法中, TR类=LomakeTaustaVari的被解析出来,但我如何才能不具有TR-类第二位?



下面是一块的HTML,它重复它的自我白衣不同的值。

 < TR类=LomakeTaustaVari> 
< TD>< DIV CLASS =Ensimmainen> 12:09< / DIV>< / TD>
< TD>< DIV> MSI< / DIV>< / TD>
< TD>< DIV> POH< / DIV>< / TD>
< TD>< DIV> 42℃; / DIV>< / TD>
< TD>< DIV> 64,50< / DIV>< / TD>
< / TR>
< TR>
< TD>< DIV CLASS =Ensimmainen> 12:09< / DIV>< / TD>
< TD>< DIV>&SRE LT; / DIV>< / TD>
< TD>< DIV> POH< / DIV>< / TD>
< TD>< DIV> 156 LT; / DIV>< / TD>
< TD>< DIV> 64,50< / DIV>< / TD>
< / TR>



我的C#代码:

  {
HtmlAgilityPack.HtmlWeb网络=新HtmlWeb();
HtmlAgilityPack.HtmlDocument DOC = web.Load(https://www.op.fi/op/henkiloasiakkaat/saastot-ja-sijoitukset/kurssit-ja-markkinat/markkinat?sivu=alltrades.html&sym= KNEBV.HSE&放大器;从= 10:00&放大器;到= 19:00和ID = 32453);

的foreach(在doc.DocumentNode.SelectNodes HtmlNode行(// TR [@类='LomakeTaustaVari']))
{
Console.WriteLine(row.InnerText );
}
Console.ReadKey();
}


解决方案

尝试使用下一个的XPath // TR [前同辈:: TR [@类='LomakeTaustaVari']]

  VAR节点= doc.DocumentNode.SelectNodes(// TR [前同辈:: TR [@类='LomakeTaustaVari']); 



应该选择那些一节点 TR 带班 LomakeTaustaVari



仅供参考:如果没有找到节点,的SelectNodes 方法的返回值


I'm trying to parse out stock exchange information whit a simple piece of C# from a HTML document. The problem is that I can not get my head around the syntax, the tr class="LomakeTaustaVari" gets parsed out but how do I get the second bit that has no tr-class?

Here's a piece of the HTML, it repeats it self whit different values.

<tr class="LomakeTaustaVari">
    <td><div class="Ensimmainen">12:09</div></td>
    <td><div>MSI</div></td>
    <td><div>POH</div></td>
    <td><div>42</div></td>
    <td><div>64,50</div></td>
</tr>
<tr>
    <td><div class="Ensimmainen">12:09</div></td>
    <td><div>SRE</div></td>
    <td><div>POH</div></td>
    <td><div>156</div></td>
    <td><div>64,50</div></td>
</tr>

My C# code:

{
    HtmlAgilityPack.HtmlWeb web = new HtmlWeb();
    HtmlAgilityPack.HtmlDocument doc = web.Load ("https://www.op.fi/op/henkiloasiakkaat/saastot-ja-sijoitukset/kurssit-ja-markkinat/markkinat?sivu=alltrades.html&sym=KNEBV.HSE&from=10:00&to=19:00&id=32453");

    foreach (HtmlNode row in doc.DocumentNode.SelectNodes("//tr[@class='LomakeTaustaVari']"))
    {
        Console.WriteLine(row.InnerText);
    }
    Console.ReadKey();
}
解决方案

Try to use the next xpath //tr[preceding-sibling::tr[@class='LomakeTaustaVari']]:

var nodes = doc.DocumentNode.SelectNodes("//tr[preceding-sibling::tr[@class='LomakeTaustaVari']]");

It should select nodes that have preceding node tr with class LomakeTaustaVari.

Just FYI: if no nodes found, SelectNodes method returns null.

这篇关于C#解析HTML使用XPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 16:45