【问题标题】:C# Web Crawler/Parser/Spider [closed]C# Web Crawler/Parser/Spider [关闭]
【发布时间】:2013-06-21 17:06:39
【问题描述】:

我是 C# 和 WinForms 的新手,我想创建一个网络爬虫(解析器)——它可以解析网页并分层显示它们。 + 我不知道如何让机器人以特定的超链接深度爬行。

所以我想我有两个问题:

  1. 如何让bot爬取指定的链接深度?
  2. 如何分层显示所有超链接?

附:如果它是代码示例,我会很棒。

附言有 1 个按钮 = button1;和 1 个富文本框 =richTextBox1;

这是我的代码:我知道它很丑......(所有代码都在一个按钮中):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        //Declaration

        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse) request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream());
        Match m;
        string anotherTest = @"(((ht){1}tp[s]?://)[-a-zA-Z0-9@:%_\+.~#?&\\]+)";
        List<string> savedUrls = new List<string>();
        List<string> titles = new List<string>();

        //Go to this URL:
        string url = UrlTextBox.Text = "http://www.yahoo.com";
        if (!(url.StartsWith("http://") || url.StartsWith("https://")))
            url = "http://" + url;

       //Scrape Whole Html code:
        string s = sr.ReadToEnd();

        try
        {
            // Get Urls:
            m = Regex.Match(s, anotherTest,
                            RegexOptions.IgnoreCase | RegexOptions.Compiled,
                            TimeSpan.FromSeconds(1));

            while (m.Success)
            {
                savedUrls.Add(m.Groups[1].ToString());
                m = m.NextMatch();
            }

            // Get TITLES:
            Match m2 = Regex.Match(s, @"<title>\s*(.+?)\s*</title>");
            if (m2.Success)
            {
                titles.Add(m2.Groups[1].Value);
            }
            //Show Title:
            richTextBox1.Text += titles[0] + "\n";

            //Show Urls:
            TrimUrls(ref savedUrls);
        }
        catch (RegexMatchTimeoutException)
        {
            Console.WriteLine("The matching operation timed out.");
        }

        sr.Close();
    }

    private void TrimUrls(ref List<string> urls)
    {
        List<string> d = urls.Distinct().ToList();
        foreach (var v in d)
        {
            if (v.IndexOf('.') != -1 && v != "http://www.w3.org")
            {
                richTextBox1.Text += v + "\n";
            }
        }
    }

}

}

还有一个问题: 有人知道如何像树一样将它保存在 XML 中吗?

【问题讨论】:

  • 简单说HTMLAgilityPack
  • Python + urllib2 + BeautifulSoup
  • 是否有机会编写代码:如何使用 HTMLAgilityPack 实现深度?
  • Python + urllib2 + BeautifulSoup - 抱歉,即使是 C# 我也是新手 :)
  • 您好,欢迎来到本网站。你的问题可能太笼统了。你具体有什么问题?

标签: c# winforms parsing web-crawler


【解决方案1】:

我也强烈推荐你HTML Agility Pack

使用 Html Agility Pack,您可以执行以下操作:

var doc = new HtmlDocument();
doc.LoadHtml(html);
var urls = new List<String>();
doc.DocumentNode.SelectNodes("//a").ForEach(x => 
{
    urls.Add(x.Attributes["href"].Value);
});

编辑:

你可以这样做,但请添加一些异常处理。

public class ParsResult
{
    public ParsResult Parent { get; set; }
    public String Url { get; set; }
    public Int32 Depth { get; set; }
}

__

private readonly List<ParsResult> _results = new List<ParsResult>();
private  Int32 _maxDepth = 5;
public  void Foo(String urlToCheck = null, Int32 depth = 0, ParsResult parent = null)
{
    if (depth >= _maxDepth) return;
    String html;
    using (var wc = new WebClient())
        html = wc.DownloadString(urlToCheck ?? parent.Url);

    var doc = new HtmlDocument();
    doc.LoadHtml(html);
    var aNods = doc.DocumentNode.SelectNodes("//a");
    if (aNods == null || !aNods.Any()) return;
    foreach (var aNode in aNods)
    {
        var url = aNode.Attributes["href"];
        if (url == null)
            continue;
        var result = new ParsResult
        {
            Depth = depth,
            Parent = parent,
            Url = url.Value
        };
        _results.Add(result);
        Console.WriteLine("{0} - {1}", depth, result.Url);
        Foo(depth: depth + 1, parent: result);
}

【讨论】:

  • 感谢您的帮助。我只需要知道如何制作一个函数(也许是递归的)来深入挖掘......
  • 请你帮我把它保存在 XML 文件中吗?提前致谢。
【解决方案2】:

如果需要解析此类结构化数据(xhtml),请尝试查看xpath:http://msdn.microsoft.com/en-us/library/ms256086.aspx

(你也应该把你的逻辑放在专用的对象中,而不是让它在 GUI 层。你以后会欣赏的。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    相关资源
    最近更新 更多