猿问

从 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 

        }

    }        

}


梵蒂冈之花
浏览 361回答 2
2回答

斯蒂芬大帝

你可以看看HTML Agility Pack:然后,您可以从网页中找到所有链接,例如:&nbsp;var hrefs = new List<string>();&nbsp;var hw = new HtmlWeb();&nbsp;HtmlDocument document = hw.Load(/* your url here */);&nbsp;foreach(HtmlNode link in document.DocumentNode.SelectNodes("//a[@href]"))&nbsp;{&nbsp; &nbsp; HtmlAttribute attribute = link.Attributes["href"];&nbsp; &nbsp; if (!string.IsNullOrWhiteSpace(attribute.Value))&nbsp; &nbsp; &nbsp; &nbsp; hrefs.Add(attribute.Value);&nbsp;}

呼唤远方

首先,您可以创建一个函数来像您所做的那样返回整个网站的 HTML 代码。这是我有的!public string GetPageContents(){&nbsp; &nbsp; string link = "https://www.abc.net.au/news/science/"&nbsp; &nbsp; string pageContent = "";&nbsp; &nbsp; WebClient web = new WebClient();&nbsp; &nbsp; Stream stream;&nbsp; &nbsp; stream = web.OpenRead(link);&nbsp; &nbsp; using (StreamReader reader = new StreamReader(stream))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; pageContent = reader.ReadToEnd();&nbsp; &nbsp; }&nbsp; &nbsp; stream.Close();&nbsp; &nbsp; return pageContents;}然后你可以创建一个函数来返回一个子字符串或一个子字符串列表(这意味着如果你想要所有 < a > 标签,你可能会得到多个标签)。List<string> divTags = GetBetweenTags(pageContents, "<div>", "</div>")这将为您提供一个列表,例如,您可以在其中再次搜索每个 < div > 标记内的 < a > 标记。public List<string> GetBetweenTags(string pageContents, string startTag, string endTag){&nbsp; &nbsp; Regex rx = new Regex(startTag + "(.*?)" + endTag);&nbsp; &nbsp; MatchCollection col = rx.Matches(value);&nbsp; &nbsp; List<string> tags = new List<string>();&nbsp; &nbsp; foreach(Match s in col)&nbsp; &nbsp; &nbsp; &nbsp; tags.Add(s.ToString());&nbsp; &nbsp; return tags;}编辑:哇不知道 HTML Agility Pack,谢谢@Gauravsa 我会更新我的项目以使用它!
随时随地看视频慕课网APP
我要回答