2014-07-10 73 views
1

我正在執行以下代碼以使用htmlagilitypack提取頁面的所有鏈接。當我輸入網址https://htmlagilitypack.codeplex.com/時,我沒有收到任何錯誤,代碼工作正常。 URL也被提取並且很好地顯示。但是,如果我輸入任何其他URL,如https://htmlagilitypack.codeplex.com/discussions/12447,那麼我會收到以下錯誤「對象引用未設置爲對象的實例」。我得到這一行錯誤htmlagilitypack提取電子郵件

OutputLabel.Text += counter + ". " + aTag.InnerHtml + " - " + 
        aTag.Attributes["href"].Value + "\t" + "<br />"; 

請幫我。這對你來說可能是一個小錯誤,但請不要標記爲負面。

var getHtmlWeb = new HtmlWeb(); 
var document = getHtmlWeb.Load(InputTextBox.Text); 
var aTags = document.DocumentNode.SelectNodes("//a"); 
int counter = 1; 

if (aTags != null) 
{ 
    foreach (var aTag in aTags) 
    { 
     OutputLabel.Text += counter + ". " + aTag.InnerHtml + " - " + 
          aTag.Attributes["href"].Value + "\t" + "<br />"; 
     counter++; 
    } 
} 
+0

你該線路上獲取對象引用錯誤:'VAR文檔= getHtmlWeb.Load(InputTextBox.Text);' – MDiesel

+0

我在aTag.Attributes [「href」]中收到錯誤。值 – user3783579

回答

4

看起來有些錨沒有HREF屬性。例如。在給定的頁面有錨:

<a name="post40566"></a> 

所以,aTag.Attributes["href"]回報null,你有,當你試圖讓這個屬性值異常。你可以改變的XPath僅選擇有此屬性的錨:

document.DocumentNode.SelectNodes("//a[@href]"); 

或驗證,如果屬性訪問其值之前存在:

if (aTag.Attributes["href"] != null) 
    // ... 

第三個選項是GetAttributeValue方法的使用,並提供一些默認值這將被顯示爲缺少的屬性:

aTag.GetAttributeValue("href", "N/A") 
+1

非常感謝。我在網上搜索了兩個小時。它工作正常。你能幫我解決其他問題嗎?如果我想忽略圖片的網址,我需要在代碼 – user3783579

+0

@ user3783579中添加什麼,實際上這是另一個問題。如果目前的問題解決了,您應該接受解決方案,如果您有其他問題,請創建新問題。這裏提示你的下一個問題 - 獲得'href'值並驗證鏈接的擴展 –