Heim  >  Fragen und Antworten  >  Hauptteil

Laden Sie Bitcoin-Preise mit dem in C# geschriebenen Html Agility Pack herunter

<p>Ich muss den Bitcoin-Preis von https://coinmarketcap.com/currencies/bitcoin/ mithilfe des Html Agility Pack abrufen. Ich verwende dieses Beispiel und es funktioniert gut: </p> <pre class="brush:php;toolbar:false;">var html = @"http://html-agility-pack.net/"; HtmlWeb web = new HtmlWeb(); var htmlDoc = web.Load(html); var node = htmlDoc.DocumentNode.SelectSingleNode("//head/title"); Console.WriteLine("Node Name: " + node.Name + "n" + node.OuterHtml);</pre> <p>XPath ist: <code>//*[@id="__next"]/div/div[1]/div[2]/div/div[1]/div[2]/div/ div[2]/div[1]/div</code></p> <p>HTML-Code: </p> <pre class="brush:php;toolbar:false;"><div class="priceValue "><span>17.162,42 $</span></div></pre> <p>Ich habe den folgenden Code ausprobiert, aber er gibt „Objektverweis nicht auf eine Instanz eines Objekts festgelegt“ zurück: </p> <pre class="brush:php;toolbar:false;">var html = @"https://coinmarketcap.com/currencies/bitcoin/"; HtmlWeb web = new HtmlWeb(); var htmlDoc = web.Load(html); var node = htmlDoc.DocumentNode.SelectSingleNode("//div[@class='priceValue']/span"); Console.WriteLine("Node Name: " + node.Name + "n" + node.InnerText);`</pre></p>
P粉156532706P粉156532706409 Tage vor642

Antworte allen(1)Ich werde antworten

  • P粉729518806

    P粉7295188062023-09-06 09:17:49

    TLDR:

    1. 你需要告诉 HtmlWeb 解压响应(或使用合适的HTTP客户端)
    2. 你需要修复XPath选择器

    显然,SelectSingleNode()调用返回null,因为它找不到节点。

    在这种情况下,检查加载的HTML是有帮助的。你可以通过获取htmlDoc.DocumentNode.InnerHtml的值来做到这一点。我尝试过这样做,生成的“HTML”是无意义的。

    原因是HtmlWeb默认不解压它收到的响应。有关详细信息,请参见github问题。如果你使用了一个合适的HTTP客户端(像这个),或者如果HtmlAgilityPack开发人员更加积极,我认为你不会遇到这个问题。

    如果你坚持使用HtmlWeb,你的代码应该如下所示:

    const string html = @"https://coinmarketcap.com/currencies/bitcoin/";
            
    var web = new HtmlWeb
    {
        AutomaticDecompression = DecompressionMethods.GZip
    };
    HtmlDocument doc = web.Load(html);
    
    HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@class='priceValue ']/span");

    请注意,你要查找的元素的类实际上是priceValue (末尾有一个空格字符),页面中还有另一个类为priceValuediv。不过,这是另一个问题,你应该最终能够找到一个更健壮的选择器。也许可以尝试这样:

    HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[contains(@class, 'priceSection')]//div[contains(@class, 'priceValue')]/span");

    Antwort
    0
  • StornierenAntwort