【问题标题】:Scraping HTML DOM elements using HtmlAgilityPack in ASP.NET在 ASP.NET 中使用 HtmlAgilityPack 抓取 HTML DOM 元素
【发布时间】:2014-11-12 11:21:16
【问题描述】:

我在 ASP.NET 中使用 HtmlAgilityPack 抓取 HTML DOM 元素。目前我的代码正在加载所有 href 链接,这意味着子链接的子链接也。但我只需要我的域 URL 的依赖 URL。我不知道如何为它编写代码。任何人都可以帮我做到这一点吗? 这是我的代码:

public void GetURL(string strGetURL)
{
    var getHtmlSource = new HtmlWeb();
    var document = new HtmlDocument(); 
try
{
    document = getHtmlSource.Load(strGetURL);
    var aTags = document.DocumentNode.SelectNodes("//a"); 
    if (aTags != null)
    {
        outputurl.Text = string.Empty;
        int _count = 0;
        foreach (var aTag in aTags)
        {
            string strURLTmp;
            strURLTmp = aTag.Attributes["href"].Value;
            if (_count != 0)
            {
                if (!CheckDuplicate(strURLTmp))
                {
                    lstResults.Add(strURLTmp);
                    outputurl.Text += strURLTmp + "\n";
                    counter++; 
                    GetURL(strURLTmp);
                }
            }
            _count++;
        }
    }
}

【问题讨论】:

  • "..depending URL of my domain URL"是什么意思

标签: c# asp.net html-agility-pack


【解决方案1】:

如果您想要获取包含特定域的 URL,您可以将 XPath 更改为:

//a[contains(@href, 'your domain here')]

或者,如果您更喜欢 LINQ 而不是 XPath:

var aTags = document.DocumentNode.SelectNodes("//a"); 
if (aTags != null)
{
    ....
    var relevantLinks = aTags.Where(o => o.GetAttributeValue("href", "")
                                          .Contains("your domain here")
                                    );
    ....
}

GetAttributeValue() 是使用 HAP 获取属性值的更好方法。该方法不返回可能导致异常的null,而是在上下文节点中找不到该属性时返回第二个参数。

【讨论】:

    猜你喜欢
    • 2011-10-30
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    相关资源
    最近更新 更多