如何使用C#抓取网站数据

.NET软件工程师 对许多人来说,这是从.NET生成PDF文件的最有效方式,因为无需学习额外的API或复杂的设计系统。
艾哈迈德·阿布马格德
2018年十月28日
更新 2024年十二月22日
分享:
This article was translated from English: Does it need improvement?
Translated
View the article in English

IronWebscraper 是一个用于网络抓取、网络数据提取和网络内容解析的 .NET 库。 这是一个易于使用的库,可以添加到 Microsoft Visual Studio 项目中,用于开发和生产。

IronWebscraper具有许多独特的功能和能力,例如控制允许和禁止的页面、对象、媒体等。它还允许管理多个身份、网络缓存以及我们将在本教程中介绍的许多其他功能。

开始使用IronWebscraper

立即在您的项目中开始使用IronWebScraper,并享受免费试用。

第一步:
green arrow pointer


目标受众

本教程面向具有基本或高级编程技能的软件开发人员,他们希望构建和实施针对高级抓取功能的解决方案(网站抓取、网站数据收集和提取、网站内容解析、网络收割)。

网页抓取一直以来都不是一项简单的任务,在C#或.NET编程环境中没有占主导地位的框架。Iron Web Scraper的诞生改变了这一现状

所需技能

  1. 使用Microsoft编程语言(如C#或VB.NET)进行编程的基本原理。

  2. 对网络技术(HTML、JavaScript、JQuery、CSS 等)及其工作原理的基本理解

  3. 基本的DOM、XPath、HTML和CSS选择器知识。

工具

  1. Microsoft Visual Studio 2010 或以上版本

  2. 浏览器的网页开发者扩展,例如Chrome的Web检查器或Firefox的Firebug。

为什么要进行网页抓取?

(原因和概念)

如果您想构建一个具有以下功能的产品或解决方案:

  1. 提取网站数据

  2. 比较多个网站的内容、价格、功能等。

  3. 扫描和缓存网站内容

    如果您有上述一个或多个原因,那么IronWebscraper是一个非常适合您需求的库。

如何安装IronWebScraper?

在创建新项目后(参见附录A),您可以通过使用NuGet自动插入库或手动安装DLL,将IronWebScraper库添加到您的项目中。

使用 NuGet 安装

要通过 NuGet 将 IronWebScraper 库添加到我们的项目中,我们可以使用可视化界面(NuGet 包管理器)或通过使用包管理器控制台的命令来进行。

使用 NuGet 软件包管理器

  1. 使用鼠标 -> 右键单击项目名称 -> 选择管理 NuGet 包

    AddIronWebscraperUsingGUI related to 使用 NuGet 软件包管理器

  2. 从浏览选项卡 -> 搜索 IronWebScraper -> 安装

    AddIronWebscraperUsingGUI2 related to 使用 NuGet 软件包管理器

  3. 点击确定

    AddIronWebscraperUsingGUI3 related to 使用 NuGet 软件包管理器

  4. 我们完成了

    AddIronWebscraperUsingGUI4 related to 使用 NuGet 软件包管理器

使用 NuGet 包控制台

  1. 从工具 -> NuGet 包管理器 -> 包管理器控制台

    AddIronWebscraperUsingConsole related to 使用 NuGet 包控制台

  2. 选择类库项目作为默认项目

  3. 运行命令 -> Install-Package IronWebScraper

    AddIronWebscraperUsingConsole1 related to 使用 NuGet 包控制台

手动安装

  1. 请访问ironsoftware.com

  2. 点击IronWebScraper或通过URL直接访问其页面https://ironsoftware.com/csharp/webscraper/

  3. 点击下载DLL。

  4. 提取已下载的压缩文件

  5. 在 Visual Studio 中右键单击项目 -> 添加 -> 引用 -> 浏览

    AddIronWebscraperUsingDll related to 手动安装

  6. 转到提取的文件夹 -> netstandard2.0 -> 然后选择所有.dll文件

    AddIronWebscraperUsingDll2 related to 手动安装

  7. 完成了!

HelloScraper - 我们的第一个IronWebScraper示例

像往常一样,我们将开始实施Hello Scraper应用程序,以使用IronWebScraper迈出我们的第一步。

  • 我们创建了一个名为“IronWebScraperSample”的新控制台应用程序。

    创建IronWebScraper示例的步骤

  1. 创建一个文件夹并命名为“HelloScraperSample”

  2. 然后创建一个新类并将其命名为“HelloScraper”

    HelloScraperAddClass related to HelloScraper - 我们的第一个IronWebScraper示例

  3. 将此代码片段添加到 HelloScraper 中
public class HelloScraper : WebScraper
{
        /// <summary>
        /// Override this method initialize your web-scraper.
        /// Important tasks will be to Request at least one start url... and set allowed/banned domain or url patterns.
        /// </summary>
        public override void Init()
        {
            License.LicenseKey = "LicenseKey"; // Write License Key
            this.LoggingLevel = WebScraper.LogLevel.All; // All Events Are Logged
            this.Request("https://blog.scrapinghub.com", Parse);
        }

        /// <summary>
        /// Override this method to create the default Response handler for your web scraper.
        /// If you have multiple page types, you can add additional similar methods.
        /// </summary>
        /// <param name="response">The http Response object to parse</param>
        public override void Parse(Response response)
        {
            // set working directory for the project
            this.WorkingDirectory = AppSetting.GetAppRoot()+ @"\HelloScraperSample\Output\";
            // Loop on all Links
            foreach (var title_link in response.Css("h2.entry-title a"))
            {
                // Read Link Text
                string strTitle = title_link.TextContentClean;
                // Save Result to File
                Scrape(new ScrapedData() { { "Title", strTitle } }, "HelloScraper.json");
            }
            // Loop On All Links
            if (response.CssExists("div.prev-post > a [href]"))
            {
                // Get Link URL
                var next_page = response.Css("div.prev-post > a [href]")[0].Attributes ["href"];
                // Scrape Next URL
                this.Request(next_page, Parse);
            }
        }
}
public class HelloScraper : WebScraper
{
        /// <summary>
        /// Override this method initialize your web-scraper.
        /// Important tasks will be to Request at least one start url... and set allowed/banned domain or url patterns.
        /// </summary>
        public override void Init()
        {
            License.LicenseKey = "LicenseKey"; // Write License Key
            this.LoggingLevel = WebScraper.LogLevel.All; // All Events Are Logged
            this.Request("https://blog.scrapinghub.com", Parse);
        }

        /// <summary>
        /// Override this method to create the default Response handler for your web scraper.
        /// If you have multiple page types, you can add additional similar methods.
        /// </summary>
        /// <param name="response">The http Response object to parse</param>
        public override void Parse(Response response)
        {
            // set working directory for the project
            this.WorkingDirectory = AppSetting.GetAppRoot()+ @"\HelloScraperSample\Output\";
            // Loop on all Links
            foreach (var title_link in response.Css("h2.entry-title a"))
            {
                // Read Link Text
                string strTitle = title_link.TextContentClean;
                // Save Result to File
                Scrape(new ScrapedData() { { "Title", strTitle } }, "HelloScraper.json");
            }
            // Loop On All Links
            if (response.CssExists("div.prev-post > a [href]"))
            {
                // Get Link URL
                var next_page = response.Css("div.prev-post > a [href]")[0].Attributes ["href"];
                // Scrape Next URL
                this.Request(next_page, Parse);
            }
        }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel
  1. 现在开始 Scrape 将以下代码片段添加到主页
static void Main(string [] args)
{
        // Create Object From Hello Scrape class
        HelloScraperSample.HelloScraper scrape = new HelloScraperSample.HelloScraper();
            // Start Scraping
            scrape.Start();
}
static void Main(string [] args)
{
        // Create Object From Hello Scrape class
        HelloScraperSample.HelloScraper scrape = new HelloScraperSample.HelloScraper();
            // Start Scraping
            scrape.Start();
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel
  1. 结果将保存在格式为 WebSraper.WorkingDirecty/classname.Json 的文件中。

    HelloScraperFrmFileResult related to HelloScraper - 我们的第一个IronWebScraper示例

代码概览

Scrape.Start() => 启动以下抓取逻辑:

  1. 首先调用 Init() 方法以初始化变量、抓取属性和行为属性。

  2. 正如我们所看到的,它将起始页面设置为 Request("https://blog.scrapinghub.com", Parse),并定义 Parse (Response response) 为用于解析响应的过程。

  3. Webscraper 并行管理:http 和线程……保持您的所有代码易于调试和同步。

  4. 在 Init() 之后启动 Parse 方法来解析页面。
    1. 您可以使用(Css 选择器、Js DOM、XPath)查找元素

    2. 选中的元素会被转换为 ScrapedData 类,您也可以将它们转换为任何自定义类(如产品、员工、新闻等)。

    3. 对象以 Json 格式保存在("bin/Scrape/")目录下的文件中。也可以将文件路径设为参数,稍后我们将在其他示例中看到。

IronWebScraper 库功能和选项

您可以在使用手动安装方法下载的zip文件内找到更新的文档(IronWebScraper Documentation.chm文件)。

或者,您可以在线查看库的最新文档更新,网址为 https://ironsoftware.com/csharp/webscraper/object-reference/

要在项目中开始使用IronWebscraper,您必须继承 (IronWebScraper.WebScraper) 类,该类扩展了您的类库并为其添加抓取功能。

您还必须实现 {Init(), Parse(Response response)} 方法。

namespace IronWebScraperEngine
{
    public class NewsScraper : IronWebScraper.WebScraper
    {
        public override void Init()
        {
            throw new NotImplementedException();
        }

        public override void Parse(Response response)
        {
            throw new NotImplementedException();
        }
    }
}
namespace IronWebScraperEngine
{
    public class NewsScraper : IronWebScraper.WebScraper
    {
        public override void Init()
        {
            throw new NotImplementedException();
        }

        public override void Parse(Response response)
        {
            throw new NotImplementedException();
        }
    }
}
Namespace IronWebScraperEngine
	Public Class NewsScraper
		Inherits IronWebScraper.WebScraper

		Public Overrides Sub Init()
			Throw New NotImplementedException()
		End Sub

		Public Overrides Sub Parse(ByVal response As Response)
			Throw New NotImplementedException()
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel
Properties \ functionsTypeDescription
Init ()Methodused to setup the scraper
Parse (Response response)MethodUsed to implement the logic that the scraper will use and how it will process it.
Coming table contain list of methods and properties that IronWebScraper Library are providing
NOTE : Can implement multiple method for different pages behaviors or structures
  • BannedUrls
  • AllowedUrls
  • BannedDomains
CollectionsUsed to ban/Allow/ URLs And/Or Domains
Ex: BannedUrls.Add ("*.zip", "*.exe", "*.gz", "*.pdf");
Note:
  • You can use ( * and/or ? ) wildcards
  • You can use strings and regular expressions
  • BannedUrls, AllowedUrls, BannedDomains, AllowedDomains
  • BannedUrls.Add ("*.zip", "*.exe", "*.gz", "*.pdf");
  • *? glob sale wildcards
  • strings and regular expressions
  • you can override this behavior by overriding the method: public virtual bool AcceptUrl (string url)
ObeyRobotsDotTxtBooleanUsed to enable or disable read and follow robots.txt its directive or not
public override bool ObeyRobotsDotTxtForHost (string Host)MethodUsed to enable or disable read and follow robots.txt its directive or not for certain domain
ScrapeMethod
ScrapeUniqueMethod
ThrottleModeEnumeration
EnableWebCache ()Method
EnableWebCache (TimeSpan cacheDuration)Method
MaxHttpConnectionLimitInt
RateLimitPerHostTimeSpan
OpenConnectionLimitPerHostInt
ObeyRobotsDotTxtBoolean
ThrottleModeEnumEnum Options:
  • ByIpAddress
  • ByDomainHostName
SetSiteSpecificCrawlRateLimit (string hostName, TimeSpan crawlRate)Method
IdentitiesCollectionsA list of HttpIdentity () to be used to fetch web resources.

Each Identity may have a different proxy IP addresses, user Agent, http headers, Persistent cookies, username and password.
Best practice is to create Identities in your WebScraper.Init Method and Add Them to this WebScraper.Identities List.
WorkingDirectorystringSetting working directory that will be used for all scrape related data will be stored to disk.


## 真实案例与实践

抓取在线电影网站

让我们从一个真实世界的网站开始另一个示例。我们将选择抓取一个电影网站。

让我们添加一个新类并将其命名为“MovieScraper”:

MovieScrapaerAddClass related to 抓取在线电影网站

现在,让我们来看看我们要搜索的网站:

123movies related to 抓取在线电影网站

这是我们在网站上看到的主页 HTML 的一部分:

<div id="movie-featured" class="movies-list movies-list-full tab-pane in fade active">
    <div data-movie-id="20746" class="ml-item">
        <a href="https://website.com/film/king-arthur-legend-of-the-sword-20746/">
            <span class="mli-quality">CAM</span>
            <img data-original="https://img.gocdn.online/2017/05/16/poster/2116d6719c710eabe83b377463230fbe-king-arthur-legend-of-the-sword.jpg" 
                 class="lazy thumb mli-thumb" alt="King Arthur: Legend of the Sword"
                  src="https://img.gocdn.online/2017/05/16/poster/2116d6719c710eabe83b377463230fbe-king-arthur-legend-of-the-sword.jpg" 
                 style="display: inline-block;">
            <span class="mli-info"><h2>King Arthur: Legend of the Sword</h2></span>
        </a>
    </div>
    <div data-movie-id="20724" class="ml-item">
        <a href="https://website.com/film/snatched-20724/" >
            <span class="mli-quality">CAM</span>
            <img data-original="https://img.gocdn.online/2017/05/16/poster/5ef66403dc331009bdb5aa37cfe819ba-snatched.jpg" 
                 class="lazy thumb mli-thumb" alt="Snatched" 
                 src="https://img.gocdn.online/2017/05/16/poster/5ef66403dc331009bdb5aa37cfe819ba-snatched.jpg" 
                 style="display: inline-block;">
            <span class="mli-info"><h2>Snatched</h2></span>
        </a>
    </div>
</div>
<div id="movie-featured" class="movies-list movies-list-full tab-pane in fade active">
    <div data-movie-id="20746" class="ml-item">
        <a href="https://website.com/film/king-arthur-legend-of-the-sword-20746/">
            <span class="mli-quality">CAM</span>
            <img data-original="https://img.gocdn.online/2017/05/16/poster/2116d6719c710eabe83b377463230fbe-king-arthur-legend-of-the-sword.jpg" 
                 class="lazy thumb mli-thumb" alt="King Arthur: Legend of the Sword"
                  src="https://img.gocdn.online/2017/05/16/poster/2116d6719c710eabe83b377463230fbe-king-arthur-legend-of-the-sword.jpg" 
                 style="display: inline-block;">
            <span class="mli-info"><h2>King Arthur: Legend of the Sword</h2></span>
        </a>
    </div>
    <div data-movie-id="20724" class="ml-item">
        <a href="https://website.com/film/snatched-20724/" >
            <span class="mli-quality">CAM</span>
            <img data-original="https://img.gocdn.online/2017/05/16/poster/5ef66403dc331009bdb5aa37cfe819ba-snatched.jpg" 
                 class="lazy thumb mli-thumb" alt="Snatched" 
                 src="https://img.gocdn.online/2017/05/16/poster/5ef66403dc331009bdb5aa37cfe819ba-snatched.jpg" 
                 style="display: inline-block;">
            <span class="mli-info"><h2>Snatched</h2></span>
        </a>
    </div>
</div>
HTML

正如我们所见,我们有电影ID、标题和详细页面链接。

让我们开始抓取这组数据:

public class MovieScraper : WebScraper
{
    public override void Init()
    {
        License.LicenseKey = "LicenseKey";
        this.LoggingLevel = WebScraper.LogLevel.All;
        this.WorkingDirectory = AppSetting.GetAppRoot() + @"\MovieSample\Output\";
        this.Request("www.website.com", Parse);
    }
    public override void Parse(Response response)
    {
        foreach (var Divs in response.Css("#movie-featured > div"))
        {
            if (Divs.Attributes ["class"] != "clearfix")
            {
                var MovieId = Divs.GetAttribute("data-movie-id");
                var link = Divs.Css("a")[0];
                var MovieTitle = link.TextContentClean;
                Scrape(new ScrapedData() { { "MovieId", MovieId }, { "MovieTitle", MovieTitle } }, "Movie.Jsonl");
            }
        }           
    }
}
public class MovieScraper : WebScraper
{
    public override void Init()
    {
        License.LicenseKey = "LicenseKey";
        this.LoggingLevel = WebScraper.LogLevel.All;
        this.WorkingDirectory = AppSetting.GetAppRoot() + @"\MovieSample\Output\";
        this.Request("www.website.com", Parse);
    }
    public override void Parse(Response response)
    {
        foreach (var Divs in response.Css("#movie-featured > div"))
        {
            if (Divs.Attributes ["class"] != "clearfix")
            {
                var MovieId = Divs.GetAttribute("data-movie-id");
                var link = Divs.Css("a")[0];
                var MovieTitle = link.TextContentClean;
                Scrape(new ScrapedData() { { "MovieId", MovieId }, { "MovieTitle", MovieTitle } }, "Movie.Jsonl");
            }
        }           
    }
}
Public Class MovieScraper
	Inherits WebScraper

	Public Overrides Sub Init()
		License.LicenseKey = "LicenseKey"
		Me.LoggingLevel = WebScraper.LogLevel.All
		Me.WorkingDirectory = AppSetting.GetAppRoot() & "\MovieSample\Output\"
		Me.Request("www.website.com", AddressOf Parse)
	End Sub
	Public Overrides Sub Parse(ByVal response As Response)
		For Each Divs In response.Css("#movie-featured > div")
			If Divs.Attributes ("class") <> "clearfix" Then
				Dim MovieId = Divs.GetAttribute("data-movie-id")
				Dim link = Divs.Css("a")(0)
				Dim MovieTitle = link.TextContentClean
				Scrape(New ScrapedData() From {
					{ "MovieId", MovieId },
					{ "MovieTitle", MovieTitle }
				},
				"Movie.Jsonl")
			End If
		Next Divs
	End Sub
End Class
$vbLabelText   $csharpLabel

此代码有什么新功能?

工作目录属性用于设置所有抓取数据及其相关文件的主工作目录。

让我们做更多。

如果我们需要构建类型化对象来保存格式化对象中的抓取数据,该怎么办?

让我们实现一个电影类,用于存放我们的格式化数据:

public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string URL { get; set; }

}
public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string URL { get; set; }

}
Public Class Movie
	Public Property Id() As Integer
	Public Property Title() As String
	Public Property URL() As String

End Class
$vbLabelText   $csharpLabel

现在,我们将更新代码:

public class MovieScraper : WebScraper
{
    public override void Init()
    {
        License.LicenseKey = "LicenseKey";
        this.LoggingLevel = WebScraper.LogLevel.All;
        this.WorkingDirectory = AppSetting.GetAppRoot() + @"\MovieSample\Output\";
        this.Request("https://website.com/", Parse);
    }
    public override void Parse(Response response)
    {
        foreach (var Divs in response.Css("#movie-featured > div"))
        {
            if (Divs.Attributes ["class"] != "clearfix")
            {
                var movie = new Movie();
                movie.Id = Convert.ToInt32( Divs.GetAttribute("data-movie-id"));
                var link = Divs.Css("a")[0];
                movie.Title = link.TextContentClean;
                movie.URL = link.Attributes ["href"];
                Scrape(movie, "Movie.Jsonl");
            }
        }
    }
}
public class MovieScraper : WebScraper
{
    public override void Init()
    {
        License.LicenseKey = "LicenseKey";
        this.LoggingLevel = WebScraper.LogLevel.All;
        this.WorkingDirectory = AppSetting.GetAppRoot() + @"\MovieSample\Output\";
        this.Request("https://website.com/", Parse);
    }
    public override void Parse(Response response)
    {
        foreach (var Divs in response.Css("#movie-featured > div"))
        {
            if (Divs.Attributes ["class"] != "clearfix")
            {
                var movie = new Movie();
                movie.Id = Convert.ToInt32( Divs.GetAttribute("data-movie-id"));
                var link = Divs.Css("a")[0];
                movie.Title = link.TextContentClean;
                movie.URL = link.Attributes ["href"];
                Scrape(movie, "Movie.Jsonl");
            }
        }
    }
}
Public Class MovieScraper
	Inherits WebScraper

	Public Overrides Sub Init()
		License.LicenseKey = "LicenseKey"
		Me.LoggingLevel = WebScraper.LogLevel.All
		Me.WorkingDirectory = AppSetting.GetAppRoot() & "\MovieSample\Output\"
		Me.Request("https://website.com/", AddressOf Parse)
	End Sub
	Public Overrides Sub Parse(ByVal response As Response)
		For Each Divs In response.Css("#movie-featured > div")
			If Divs.Attributes ("class") <> "clearfix" Then
				Dim movie As New Movie()
				movie.Id = Convert.ToInt32(Divs.GetAttribute("data-movie-id"))
				Dim link = Divs.Css("a")(0)
				movie.Title = link.TextContentClean
				movie.URL = link.Attributes ("href")
				Scrape(movie, "Movie.Jsonl")
			End If
		Next Divs
	End Sub
End Class
$vbLabelText   $csharpLabel

有什么新功能?

  1. 我们实现电影类来存储我们抓取的数据。

  2. 我们将电影对象传递给Scrape方法,它理解我们的格式并按照我们在这里看到的定义格式进行保存:

    MovieResultMovieClass related to 抓取在线电影网站

    让我们开始抓取一个更详细的页面。

电影页面如下:

MovieDetailsSample related to 抓取在线电影网站

```html

Guardians of the Galaxy Vol. 2

Set to the backdrop of Awesome Mixtape #2, Marvel's Guardians of the Galaxy Vol. 2 continues the team's adventures as they travel throughout the cosmos to help Peter Quill learn more about his true parentage.

Duration: 136 min

Quality: CAM

Release: 2017

IMDb: 8.3

``` 我们可以通过新属性(描述、类型、演员、导演、国家、时长、IMDB评分)扩展我们的电影类,但我们将仅使用(描述、类型、演员)用于我们的示例。 ```cs public class Movie { public int Id { get; set; } public string Title { get; set; } public string URL { get; set; } public string Description { get; set; } public ListGenre { get; set; } public ListActor { get; set; } } ``` 现在我们将导航到详细页面进行抓取。 IronWebScraper 允许您添加更多的抓取功能,以抓取不同类型的页面格式。 如我们所见: ```cs public class MovieScraper : WebScraper { public override void Init() { License.LicenseKey = "LicenseKey"; this.LoggingLevel = WebScraper.LogLevel.All; this.WorkingDirectory = AppSetting.GetAppRoot() + @"\MovieSample\Output\"; this.Request("https://domain/", Parse); } public override void Parse(Response response) { foreach (var Divs in response.Css("#movie-featured > div")) { if (Divs.Attributes ["class"] != "clearfix") { var movie = new Movie(); movie.Id = Convert.ToInt32( Divs.GetAttribute("data-movie-id")); var link = Divs.Css("a")[0]; movie.Title = link.TextContentClean; movie.URL = link.Attributes ["href"]; this.Request(movie.URL, ParseDetails, new MetaData() { { "movie", movie } });// to scrap Detailed Page } } } public void ParseDetails(Response response) { var movie = response.MetaData.Get("movie"); var Div = response.Css("div.mvic-desc")[0]; movie.Description = Div.Css("div.desc")[0].TextContentClean; foreach(var Genre in Div.Css("div > p > a")) { movie.Genre.Add(Genre.TextContentClean); } foreach (var Actor in Div.Css("div > p:nth-child(2) > a")) { movie.Actor.Add(Actor.TextContentClean); } Scrape(movie, "Movie.Jsonl"); } } ``` *有什么新功能?* 1. 我们可以添加抓取功能(ParseDetails)来抓取详细页面 2. 我们将生成文件的 Scrape 功能移至新功能。 3. 我们使用了IronWebscraper功能(MetaData)将我们的电影对象传递给新的抓取功能 4. 我们爬取了页面并将我们的电影对象数据保存到了一个文件中。

MovieResultMovieClass1 related to 抓取在线电影网站

### 从购物网站抓取内容 我们选择一个购物网站来抓取其内容。

ShoppingSite related to 抓取在线电影网站

如您从图片中可以看到,我们有一个左侧栏,其中包含了网站产品类别的链接。 因此,我们的第一步是调查网站的HTML,并计划我们希望如何抓取它。

ShoppingSiteLeftBar related to 抓取在线电影网站

时尚网站类别有子类别(男士、女士、儿童) ```html``` 让我们建立一个项目 1. 创建一个新的控制台应用程序或为我们的新示例添加一个名为“ShoppingSiteSample”的新文件夹。 2. 添加名为“ShoppingScraper”的新类 3. 首先将抓取网站的类别及其子类别。 让我们创建一个类别模型: ```cs public class Category { ////// Gets or sets the name. ///////// The name. ///public string Name { get; set; } ////// Gets or sets the URL. ///////// The URL. ///public string URL { get; set; } ////// Gets or sets the sub categories. ///////// The sub categories. ///public ListSubCategories { get; set; } } ``` 4. 现在,让我们构建刮擦逻辑 ```cs public class ShoppingScraper : WebScraper { ////// Override this method initialize your web-scraper. /// Important tasks will be to Request at least one start url... and set allowed/banned domain or url patterns. ///public override void Init() { License.LicenseKey = "LicenseKey"; this.LoggingLevel = WebScraper.LogLevel.All; this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\"; this.Request("www.webSite.com", Parse); } ////// Override this method to create the default Response handler for your web scraper. /// If you have multiple page types, you can add additional similar methods. //////The http Response object to parsepublic override void Parse(Response response) { var categoryList = new List(); foreach (var Links in response.Css("#menuFixed > ul > li > a ")) { var cat = new Category(); cat.URL = Links.Attributes ["href"]; cat.Name = Links.InnerText; categoryList.Add(cat); } Scrape(categoryList, "Shopping.Jsonl"); } } ``` 从菜单中抓取链接

ShoppingSiteScrapeMenu related to 抓取在线电影网站

让我们更新代码,以抓取主分类及其所有子链接 ```cs public override void Parse(Response response) { // List of Categories Links (Root) var categoryList = new List(); foreach (var li in response.Css("#menuFixed > ul > li")) { // List Of Main Links foreach (var Links in li.Css("a")) { var cat = new Category(); cat.URL = Links.Attributes ["href"]; cat.Name = Links.InnerText; cat.SubCategories = new List(); // List of Sub Catgories Links foreach (var subCategory in li.Css("a [class=subcategory]")) { var subcat = new Category(); subcat.URL = Links.Attributes ["href"]; subcat.Name = Links.InnerText; // Check If Link Exist Before if (cat.SubCategories.Find(c=>c.Name== subcat.Name && c.URL == subcat.URL) == null) { // Add Sublinks cat.SubCategories.Add(subcat); } } // Add Categories categoryList.Add(cat); } } Scrape(categoryList, "Shopping.Jsonl"); } ``` 现在我们有了指向所有网站类别的链接,让我们开始抓取每个类别中的产品。 让我们导航到任何类别并检查内容。

ProductSubCategoryList related to 抓取在线电影网站

让我们看看它的代码 ```html
``` 让我们为这些内容建立产品模型。 ```cs public class Product { ////// Gets or sets the name. ///////// The name. ///public string Name { get; set; } ////// Gets or sets the price. ///////// The price. ///public string Price { get; set; } ////// Gets or sets the image. ///////// The image. ///public string Image { get; set; } } ``` 为了抓取分类页面,我们添加了一种新的抓取方法: ```cs public void ParseCatgory(Response response) { // List of Products Links (Root) var productList = new List(); foreach (var Links in response.Css("body > main > section.osh-content > section.products > div > a")) { var product = new Product(); product.Name = Links.InnerText; product.Image = Links.Css("div.image-wrapper.default-state > img")[0].Attributes ["src"]; productList.Add(product); } Scrape(productList, "Products.Jsonl"); } ``` ### 高级网页抓取功能 #### HttpIdentity 功能: 一些网站系统要求用户登录后才能查看内容; 在这种情况下,我们可以使用HttpIdentity:- ```cs HttpIdentity id = new HttpIdentity(); id.NetworkUsername = "username"; id.NetworkPassword = "pwd"; Identities.Add(id); ``` 在IronWebScraper中,最令人印象深刻和强大的功能之一是使用数千个独特的(用户凭证和/或浏览器引擎)通过多登录会话来伪装或抓取网站的能力。 ```cs public override void Init() { License.LicenseKey = " LicenseKey "; this.LoggingLevel = WebScraper.LogLevel.All; this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\"; var proxies = "IP-Proxy1: 8080,IP-Proxy2: 8081".Split(','); foreach (var UA in IronWebScraper.CommonUserAgents.ChromeDesktopUserAgents) { foreach (var proxy in proxies) { Identities.Add(new HttpIdentity() { UserAgent = UA, UseCookies = true, Proxy = proxy }); } } this.Request("http://www.Website.com", Parse); } ``` 您拥有多个属性以赋予您不同的行为,因此可以防止网站屏蔽您。 一些这些属性:- * **NetworkDomain**:用于用户身份验证的网络域。 支持 Windows、NTLM、Keroberos、Linux、BSD 和 Mac OS X 网络。 必须与(NetworkUsername 和 NetworkPassword)一起使用 * **NetworkUsername**:用于用户身份验证的网络/HTTP用户名。 支持Http、Windows网络、NTLM、Kerberos、Linux网络、BSD网络和Mac OS。 * **NetworkPassword**:用于用户身份验证的网络/HTTP密码。 支持Http、Windows网络、NTLM、Keroberos、Linux网络、BSD网络和Mac OS。 * **代理**:设置代理设置 * **UserAgent**:用于设置浏览器引擎(chrome桌面版、chrome手机版、chrome平板版、IE和Firefox等)。 * **HttpRequestHeaders**:用于此身份的自定义标头值,并且接受字典对象(Dictionary) * **UseCookies** : 启用/禁用使用Cookies IronWebScraper 使用随机身份运行抓取程序。 如果我们需要指定使用特定身份来解析页面,我们可以这样做。 ```cs public override void Init() { License.LicenseKey = " LicenseKey "; this.LoggingLevel = WebScraper.LogLevel.All; this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\"; HttpIdentity identity = new HttpIdentity(); identity.NetworkUsername = "username"; identity.NetworkPassword = "pwd"; Identities.Add(id); this.Request("http://www.Website.com", Parse, identity); } ``` #### 启用网页缓存功能: 此功能用于缓存请求的页面。 它经常在开发和测试阶段使用; 使开发者能够缓存所需页面以在更新代码后重用。 这使您可以在重新启动网络抓取工具后在缓存页面上执行代码,而不需要每次都连接到实时网站(操作重放)。 *您可以在 Init() 方法中使用它* 启用网页缓存(); 或 启用Web缓存(TimeSpan到期时间); 它会将缓存数据保存到工作目录下的WebCache文件夹中。 ```cs public override void Init() { License.LicenseKey = " LicenseKey "; this.LoggingLevel = WebScraper.LogLevel.All; this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\"; EnableWebCache(new TimeSpan(1,30,30)); this.Request("http://www.WebSite.com", Parse); } ``` IronWebScraper 还具有功能,可以通过使用 Start(CrawlID) 设置引擎启动过程名称,使您的引擎在重新启动代码后继续抓取。 ```cs static void Main(string [] args) { // Create Object From Scraper class EngineScraper scrape = new EngineScraper(); // Start Scraping scrape.Start("enginestate"); } ``` 执行请求和响应将保存在工作目录内的 SavedState 文件夹中。 #### 限流 我们可以控制每个域的最小和最大连接数量以及连接速度。 ```cs public override void Init() { License.LicenseKey = "LicenseKey"; this.LoggingLevel = WebScraper.LogLevel.All; this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\"; // Gets or sets the total number of allowed open HTTP requests (threads) this.MaxHttpConnectionLimit = 80; // Gets or sets minimum polite delay (pause)between request to a given domain or IP address. this.RateLimitPerHost = TimeSpan.FromMilliseconds(50); // Gets or sets the allowed number of concurrent HTTP requests (threads) per hostname // or IP address. This helps protect hosts against too many requests. this.OpenConnectionLimitPerHost = 25; this.ObeyRobotsDotTxt = false; // Makes the WebSraper intelligently throttle requests not only by hostname, but // also by host servers' IP addresses. This is polite in-case multiple scraped domains // are hosted on the same machine. this.ThrottleMode = Throttle.ByDomainHostName; this.Request("https://www.Website.com", Parse); } ``` **节流属性** * **MaxHttpConnectionLimit**
允许的打开HTTP请求(线程)的总数 * **RateLimitPerHost**
对给定域或 IP 地址的请求之间的最小礼貌延迟或暂停(以毫秒为单位) * **OpenConnectionLimitPerHost**
允许的并发HTTP请求(线程)数量 * **ThrottleMode**
使 WebScraper 智能地限制请求,不仅按主机名,还按主机服务器的 IP 地址进行限制。 这是礼貌的做法,以防多个抓取的域名托管在同一台机器上。 ## 附录 ### 如何创建Windows窗体应用程序? 我们应该使用Visual Studio 2013或更高版本来进行这项工作。 按照以下步骤创建新的Windows Forms项目: 1. 打开 Visual Studio

Enterprise2015 related to 抓取在线电影网站

2. 文件 -> 新建 -> 项目

FileNewProject related to 抓取在线电影网站

3. 从模板中,选择编程语言(Visual C# 或 VB)-> Windows -> Windows 窗体应用程序

CreateWindowsApp related to 抓取在线电影网站

**项目名称**: IronScraperSample
**位置**: 选择硬盘上的位置

WindowsAppMainScreen related to 抓取在线电影网站

### 如何创建网页表单应用程序? 您应该使用Visual Studio 2013或更高版本。 按照以下步骤创建一个新的Asp.NET Web表单项目。 1. 打开 Visual Studio

Enterprise2015 related to 抓取在线电影网站

2. 文件 -> 新建 -> 项目

FileNewProject related to 抓取在线电影网站

3. 从模板中选择编程语言(Visual C# 或 VB)→ Web → ASP.NET Web 应用程序 (.NET Framework)。

ASPNETWebApplication related to 抓取在线电影网站

**项目名称**: IronScraperSample
**位置**:从硬盘中选择一个位置 4. 从您的 ASP.NET 模板
  1. 选择空模板
  2. 检查网络表格
  3. ASPNETTemplates related to 抓取在线电影网站

5. 现在,您的基本 ASP.NET 网络表单项目已经创建

ASPNETWebFormProject related to 抓取在线电影网站

[点击这里](/downloads/assets/tutorials/webscraping-in-c-sharp/IronWebScraperSample.zip) 下载完整的教程示例项目代码项目。
.NET软件工程师 对许多人来说,这是从.NET生成PDF文件的最有效方式,因为无需学习额外的API或复杂的设计系统。
艾哈迈德·阿布马格德
跨国IT公司的.NET软件解决方案架构师

Ahmed 是一位经验丰富且经过认证的微软技术专家,拥有超过10年的IT和软件开发经验。他曾在多家公司工作过,现在是一家跨国IT公司的国家经理。

Ahmed 使用 IronPDF 和 IronWebScraper 已超过一年,已在公司多个项目中使用它们。