簡體   English   中英

使用HTMLAgilityPack找不到節點

[英]Can't find node using HTMLAgilityPack

我使用了以下視頻中的代碼示例: https//youtu.be/8e3Wklc1H_A

代碼看起來像這樣

var webGet = new HtmlWeb();
var doc = webGet.Load("http://pastebin.com/raw.php?i=gF0DG08s");

HtmlNode OurNone = doc.DocumentNode.SelectSingleNode("//div[@id='footertext']");

if (OurNone != null)
    richTextBox1.Text = OurNone.InnerHtml;
else
    richTextBox1.Text = "nothing found";

我一開始以為原來的網站可能已經關閉了(www.fuchsonline.com)所以我很快就制作了一個只有一個頁腳的HTML並將其粘貼在Pastebin上(上面的代碼鏈接)

<html>
<body>

<div id="footertext">
                 <p>
                     Copyright &copy; FUCHS Online Ltd, 2013. All Rights Reserved.
                 </p>
</div>

</body>
</html>

當在代碼中使用Pastebin鏈接時,程序總是將“nothing found”寫入richTextBox。 但是,視頻中使用的網站仍在使用,因此我嘗試在webGet中使用該網站並且瞧 - 它有效。

現在我想問一下每個代碼到底出了什么問題。 HTML是否遺漏了某些內容,或者僅針對完整網站制作了該程序,如果是,是什么讓網站完整?

這是一個更簡單的方法:

WebClient webClient = new WebClient();
string htmlCode = webClient.DownloadString("http://pastebin.com/raw.php?i=gF0DG08s");

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(htmlCode);

HtmlNode OurNone = doc.DocumentNode.SelectSingleNode("//div[@id='footertext']");

if (OurNone != null)
    richTextBox1.Text = OurNone.InnerHtml;
else
    richTextBox1.Text = "nothing found";

在這種情況下,您只是將原始html作為字符串保存到此頁面,這就是它返回空的原因。 如果你真的想用HTML敏捷包解析它,你可以先下載頁面,獲取原始HTML,然后將其解析為敏捷包的文檔模型。

        WebRequest webRequest = HttpWebRequest.Create("http://pastebin.com/raw.php?i=gF0DG08s");
        webRequest.Method = "GET";
        string pageSource;
        using (StreamReader reader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
        {
            pageSource = reader.ReadToEnd();
            HtmlDocument html = new HtmlDocument();
            html.LoadHtml(pageSource);
            HtmlNode OurNone = html.DocumentNode.SelectSingleNode("//div[@id='footertext']");
            if (OurNone != null)
            {
                richTextBox1.Text = OurNone.InnerHtml;
            }
            else
            {
                richTextBox1.Text = "nothing found";
            }
        } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM