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代碼:

<a href="/title/tt4972582/?pf_rd_m=A2FGELUUNOQJNL&amp;pf_rd_p=2240084082&amp;pf_rd_r=1QW31NGD6JSE46F79CKQ&amp;pf_rd_s=center-1&amp;pf_rd_t=15506&amp;pf_rd_i=moviemeter&amp;ref_=chtmvm_tt_1" title="M. Night Shyamalan (dir.), James McAvoy, Anya Taylor-Joy">Split</a>

MessageBox顯示“Split”的文本。但看看這個Html代碼:

<div class="summary_text" itemprop="description">
                Three girls are kidnapped by a man with a diagnosed 23 distinct personalities, and must try and escape before the apparent emergence of a frightful new 24th.
        </div>

我希望MessageBox顯示以“Three girls are kidn ...”開頭的文本,所以我寫了這段代碼:

        WebClient client2 = new WebClient();
        client2.Encoding = Encoding.UTF8;
        HtmlAgilityPack.HtmlDocument doc2 = new HtmlAgilityPack.HtmlDocument();
        doc2.LoadHtml(client2.DownloadString("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"));
        MessageBox.Show(doc2.DocumentNode.SelectSingleNode("//*[@id='title - overview - widget']/div[3]/div[1]/div[1]").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合法嗎? 是的,了解原因