Html Agility Pack,SelectSingleNode

.net c# html-agility-pack

这段代码有效

        WebClient client = new WebClient();
        client.Encoding = Encoding.UTF8;
        html = client.DownloadString("http://www.imdb.com/chart/moviemeter?ref_=nv_mv_mpm_8");
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);
        MessageBox.Show(doc.DocumentNode.SelectSingleNode("//*[@id='main']/div/span/div/div/div[3]/table/tbody/tr[1]/td[2]/a").InnerText);

这里的Html代码:

        WebClient client = new WebClient();
        client.Encoding = Encoding.UTF8;
        html = client.DownloadString("http://www.imdb.com/chart/moviemeter?ref_=nv_mv_mpm_8");
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);
        MessageBox.Show(doc.DocumentNode.SelectSingleNode("//*[@id='main']/div/span/div/div/div[3]/table/tbody/tr[1]/td[2]/a").InnerText);

MessageBox显示“Split”的文本。但看看这个Html代码:

        WebClient client = new WebClient();
        client.Encoding = Encoding.UTF8;
        html = client.DownloadString("http://www.imdb.com/chart/moviemeter?ref_=nv_mv_mpm_8");
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);
        MessageBox.Show(doc.DocumentNode.SelectSingleNode("//*[@id='main']/div/span/div/div/div[3]/table/tbody/tr[1]/td[2]/a").InnerText);

我希望MessageBox显示以“Three girls are kidn ...”开头的文本,所以我写了这段代码:

        WebClient client = new WebClient();
        client.Encoding = Encoding.UTF8;
        html = client.DownloadString("http://www.imdb.com/chart/moviemeter?ref_=nv_mv_mpm_8");
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);
        MessageBox.Show(doc.DocumentNode.SelectSingleNode("//*[@id='main']/div/span/div/div/div[3]/table/tbody/tr[1]/td[2]/a").InnerText);

当我启动此代码时,发生了类型为“System.NullReferenceException”的未处理异常

Xpath是真的,我已经检查了一百次,所以我该怎么办?

一般承认的答案

你能试试吗?

        HtmlWeb web = new HtmlWeb();
        HtmlDocument doc = web.Load("http://www.imdb.com/title/tt4972582/?pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=2240084082&pf_rd_r=1QW31NGD6JSE46F79CKQ&pf_rd_s=center-1&pf_rd_t=15506&pf_rd_i=moviemeter&ref_=chtmvm_tt_1");
        var desNodeText = doc.DocumentNode.Descendants("div").FirstOrDefault(o => o.GetAttributeValue("class", "") == "summary_text").InnerText;   



许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因