首页 > 解决方案 > 从 HTML 字符串中提取 HREF 值

问题描述

我正在尝试创建一个只返回来自网站的链接的爬虫,并且我让它返回 HTML 脚本。我现在想使用 if 语句来检查字符串是否返回,如果返回,它会搜索所有“< a >”标签并向我显示 href 链接。但我不知道要检查什么对象或应该检查什么值。

这是我到目前为止所拥有的:

namespace crawler
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            string WebData wc.DownloadString("https://www.abc.net.au/news/science/");
            Console.WriteLine(WebData);
            // if 
        }
    }        
}

标签: c#webclient

解决方案


你可以看看HTML Agility Pack:

然后,您可以从网页中找到所有链接,例如:

 var hrefs = new List<string>();
 var hw = new HtmlWeb();
 HtmlDocument document = hw.Load(/* your url here */);
 foreach(HtmlNode link in document.DocumentNode.SelectNodes("//a[@href]"))
 {
    HtmlAttribute attribute = link.Attributes["href"];

    if (!string.IsNullOrWhiteSpace(attribute.Value))
        hrefs.Add(attribute.Value);
 }

推荐阅读