2012-11-14 35 views
1

我使用的是asp.net Webmatrix-Razor。我也在使用HTMLAgilityPack。我解析元標籤以從網站抓取Facebook元標籤發佈到我的網站。該代碼適用於所有網站,除非我試圖從赫芬頓郵報中獲取新聞文章。我得到「System.NullReferenceException:對象引用未設置爲對象的實例。」選擇新的行時會發生錯誤。該網站確實有Facebook元標籤。有這個meta標籤,我聽說可能會導致一個問題不確定。System.NullReferenceException與赫芬頓郵政網站

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" > 

這是代碼;

var webGet = new HtmlWeb(); 
    var document = webGet.Load(Request.Form["news_URL"]); 
    var metaTags = document.DocumentNode.SelectNodes(".//meta"); 
    if (metaTags != null){ 
     var metaOnPage = from lnks in document.DocumentNode.Descendants() 
       where lnks.Name == "meta" && 
       lnks.Attributes["property"] != null 
       //lnks.InnerText.Trim().Length > 0 
       select new 
       { 
       metaName = lnks.Attributes["property"].Value, 
       metaContent = lnks.Attributes["content"].Value 
       }; 

     var Title = ""; 
     var URL = ""; 
     var imgSRC = ""; 
     var Description = ""; 
     foreach(var i in metaOnPage){ 

     if(i.metaName == "og:title"){ 
      Title = i.metaContent; 
     }else if(i.metaName == "og:url"){ 
      URL = i.metaContent; 
     }else if(i.metaName == "og:image"){ 
      imgSRC = i.metaContent; 
     }else if(i.metaName == "og:description"){ 
      Description = i.metaContent; 
     } 

    } 

回答

2

似乎似乎這個表達式是問題:lnks.Attributes["content"].Value。你已經檢查過「屬性」存在,但不是「內容」。也許你想添加的檢查,因爲你的代碼似乎認爲內容包含的東西:

lnks.Attributes["property"] != null && lnks.Attributes["content"] != null 
+1

這做到了..感謝 – user1822433

+1

@ user1822433 - 然後請註明出任答案。 –