【问题标题】:C# Getting The HTML of the Links(Content) from WebsiteC# 从网站获取链接(内容)的 HTML
【发布时间】:2011-11-07 23:43:29
【问题描述】:

我想要的是,从网站(来自 HtmlContent)打开一个链接 并获取这个新打开的站点的 Html..

示例:我有 www.google.com,现在我想查找所有链接。 对于每个链接,我都希望拥有新站点的 HTMLContent。

我会这样做:

foreach (String link in GetLinksFromWebsite(htmlContent))
            {
                using (var client = new WebClient())
                {
                    htmlContent = client.DownloadString("http://" + link);
                }

                foreach (Match treffer in istBildURL)
                {
                    string bildUrl = treffer.Groups[1].Value;
                    bildLinks.Add(bildUrl);
                }
            }




   public static List<String> GetLinksFromWebsite(string htmlSource)
    {
        string linkPattern = "<a href=\"(.*?)\">(.*?)</a>";
        MatchCollection linkMatches = Regex.Matches(htmlSource, linkPattern, RegexOptions.Singleline);
        List<string> linkContents = new List<string>();
        foreach (Match match in linkMatches)
        {
            linkContents.Add(match.Value);
        }
        return linkContents;
    }

另一个问题是,我只得到链接,而不是链接按钮 (ASP.NET).. 我该如何解决这个问题?

【问题讨论】:

  • 你真的应该使用 Html 解析器,比如 HtmlAgilityPack

标签: c# html hyperlink


【解决方案1】:

要遵循的步骤:

  1. 下载Html Agility Pack
  2. 引用您在项目中下载的程序集
  3. 从您的项目中抛出以单词regexregular expression 开头并处理HTML 解析的所有内容(阅读this answer 以更好地理解原因)。在您的情况下,这将是 GetLinksFromWebsite 方法的内容。
  4. 只需调用 Html Agility Pack 解析器即可替换您丢弃的内容。

这里是an example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using HtmlAgilityPack;

class Program
{
    static void Main()
    {
        using (var client = new WebClient())
        {
            var htmlSource = client.DownloadString("http://www.stackoverflow.com");
            foreach (var item in GetLinksFromWebsite(htmlSource))
            {
                // TODO: you could easily write a recursive function
                // that will call itself here and retrieve the respective contents
                // of the site ...
                Console.WriteLine(item);
            }
        }
    }

    public static List<String> GetLinksFromWebsite(string htmlSource)
    {
        var doc = new HtmlDocument();
        doc.LoadHtml(htmlSource);
        return doc
            .DocumentNode
            .SelectNodes("//a[@href]")
            .Select(node => node.Attributes["href"].Value)
            .ToList();
    }
}

【讨论】:

  • thx 4 答案,我将对其进行测试并提供反馈并标记答案是否有效:D
猜你喜欢
  • 2020-06-30
  • 1970-01-01
  • 2016-11-28
  • 2017-04-14
  • 2016-03-23
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 2016-03-05
相关资源
最近更新 更多