【问题标题】:Crawl a range of pages [closed]抓取一系列页面[关闭]
【发布时间】:2012-01-27 10:54:36
【问题描述】:

我是 C# 新手,想知道抓取一系列页面的最佳方法。

如果我想获取许多这样的页面的来源: http://website.com/list/1 - http://website.com/list/44

如何让它抓取1-44范围内的每一页?

谢谢:)

【问题讨论】:

  • 您是 C# 新手。没关系,我也是初中生……但是,你来这里之前有没有用过谷歌(用 C# 抓取网页)?

标签: c# web-crawler


【解决方案1】:

这是一种不错且简单的方法,不是最通用的网络爬虫,但可以帮助您了解当前的规范

for(int i = 1; i < 45;i++){
string url = "http://website.com/list/"+i;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
myResponse.Close();
//do something with the result
}

您必须将其添加到您的 using 语句中

using System.Text;
using System.Net;
using System.IO;

亲切的问候

【讨论】:

    【解决方案2】:

    尝试类似...

    WebClient wc = new WebClient();
    for(int i = 1; i < 45 ; i++)
    {
        var pageContent = wc.DownloadString("http://website.com/list/" + i);
        // do your page content processing here
    }
    

    虽然很明显你会想为此添加错误处理。


    根据您应用的目标是什么,您可能需要在使用后调用 WebClient 上的 Dispose()。在某些环境中,WebClient 实现了 IDisposable,而在其他环境中则没有。感谢 cmets 中的@Paulo Moretti 提及。

    【讨论】:

    • s/website.com/stackoverflow.com/ - s/list/questions/ - 或者你可以去下载开放数据:-D
    • @Paulo Moretti - 取决于应用程序类型。例如,在 Windows Phone 领域,它确实实现了 IDisposable,因此在答案中不提及它更容易。
    • @ZombieSheep 你的反对是有效的。我刚刚指出,因为通常人们用 C# 标记问题时谈论的是 .NET,而不是 Silverlight。
    • @Paulo Moretti - 我会更新答案以提及它。谢谢。
    猜你喜欢
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2022-01-03
    • 2015-03-27
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多