htmlagilitpack提取电子邮件

本文关键字:电子邮件 提取 htmlagilitpack | 更新日期: 2023-09-27 18:12:24

我正在执行以下代码,以使用htmlililitypack提取页面的所有链接。当我输入URL https://htmlagilitypack.codeplex.com/时,我没有得到任何错误,代码工作正常。url也可以很好地提取和显示。但是,如果我输入任何其他URL,如https://htmlagilitypack.codeplex.com/discussions/12447,那么我得到以下错误"对象引用未设置为对象的实例"。这一行出现了错误

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++;
    }
}

htmlagilitpack提取电子邮件

看起来有些锚没有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")