[初探爬蟲框架: DotnetSpider] 一 採集博客園

来源:http://www.cnblogs.com/shensigzs/archive/2016/05/25/5528685.html
-Advertisement-
Play Games

今天ModestMT.Zou發佈了DotnetSpider爬蟲第二章節,內容簡單明瞭,基本看懂了,於是想自己試試看,直接就拿博客園開刀了。 這裡有最基本的使用方式,本文章不介紹 [開源 .NET 跨平臺 數據採集 爬蟲框架: DotnetSpider] [二] 最基本,最自由的使用方式 這裡我已經從 ...


今天ModestMT.Zou發佈了DotnetSpider爬蟲第二章節,內容簡單明瞭,基本看懂了,於是想自己試試看,直接就拿博客園開刀了。

這裡有最基本的使用方式,本文章不介紹

[開源 .NET 跨平臺 數據採集 爬蟲框架: DotnetSpider] [二] 最基本,最自由的使用方式

這裡我已經從https://github.com/zlzforever/DotnetSpider上下載代碼並編譯通過

這裡用的是VS2015,因為此項目有些C#6.0語法糖

首先,用VS2015新建一個控制項台程式,命名為DotnetSpiderDemo

 

新建一個數據對象

 

public class Cnblog
    {
        public string Title { get; set; }

        public string Url { get; set; }

        public string Author { get; set; }

        public string Conter { get; set; }
    }

  

 先引用兩個Dll類庫

Java2Dotnet.Spider.Core.dll

Newtonsoft.Json.dll

如果你編譯DotnetSpider成功的話,可以在output目錄中找到

現在來寫數據處理器,實現 IPageProcessor 這個介面

/// <summary>
    /// 頁面列表處理器
    /// </summary>
    public class PageListProcessor : IPageProcessor
    {
        public Site Site{get; set; }

        public void Process(Page page)
        {
            var totalCnblogElements = page.Selectable.SelectList(Selectors.XPath("//div[@class='post_item']")).Nodes();
            List<Cnblog> results = new List<Cnblog>();
            foreach (var cnblogElement in totalCnblogElements)
            {
                var cnblog = new Cnblog();
                cnblog.Title = cnblogElement.Select(Selectors.XPath(".//div[@class='post_item_body']/h3/a")).GetValue();
                cnblog.Url = cnblogElement.Select(Selectors.XPath(".//div[@class='post_item_body']/h3")).Links().GetValue();
                cnblog.Author = cnblogElement.Select(Selectors.XPath(".//div[@class='post_item_foot']/a[1]")).GetValue();
                results.Add(cnblog);
            }
            page.AddResultItem("Result", results);
        }
    }

  

關於XPath,可以到這裡學習http://www.w3school.com.cn/xpath/,我也是下午剛看了一遍,因為有XML/HTML基礎,基本沒壓力

關於XPath表達式如何寫,我覺得用谷歌審核元素就足夠了,可以複製XPath。也有一款谷歌XPath插件,因我翻不了牆,就沒安裝。

如下圖://*[@id="post_list"]/div[20]/div[2]/h3/a,然後再按需改改

 

數據存取

需要實現 IPipeline這個介面,然後你想保存到文件或資料庫就自己選擇

public class ListPipeline : IPipeline
    {
        private string _path;

        public ListPipeline(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new Exception("文件名不能為空!");
            }

            _path = path;

            if (!File.Exists(_path))
            {
                File.Create(_path);
            }
        }
        public void Dispose()
        {
        }

        public void Process(ResultItems resultItems, ISpider spider)
        {
            lock (this)
            {
                foreach (Cnblog entry in resultItems.Results["Result"])
                {
                    File.AppendAllText(_path, JsonConvert.SerializeObject(entry));
                }
            }
        }

  

接下來在Program的Main方法中寫運行代碼

class Program
    {
        static void Main(string[] args)
        {
            var site = new Site() { EncodingName = "UTF-8" };
            for (int i = 1; i <= 30; i++)//30頁
            {
                site.AddStartUrl(
                    $"http://www.cnblogs.com/p{i}");//已更正去掉#號,本來是"http://www.cnblogs.com/#p{i}",這樣發現請求的是http://www.cnblogs.com
            }
            
            Spider spider = Spider.Create(site, new PageListProcessor(), new QueueDuplicateRemovedScheduler()).AddPipeline(new ListPipeline("test.json")).SetThreadNum(2);//兩個線程
            spider.Run();
            Console.Read();
        }
    }

  

 

 

這樣每一頁信息就被保存起來了,但到這裡還沒完,一般情況不僅僅是採集列表頁,也會採集詳細頁,於是我又添加了兩個類,暫時我是這樣實現的,但感覺有點慢

 

添加頁面詳細數據處理器

/// <summary>
    /// 頁面詳細處理器
    /// </summary>
    public class PageDetailProcessor : IPageProcessor
    {
        private Cnblog cnblog;
        public PageDetailProcessor(Cnblog _cnblog)
        {
            cnblog = _cnblog;
        }
        public Site Site { get; set; }

        public void Process(Page page)
        {
            cnblog.Conter=page.Selectable.Select(Selectors.XPath("//*[@id='cnblogs_post_body']")).GetValue();
            page.AddResultItem("detail",cnblog);
        }
    }

  

再添加頁面詳細數據保存

public class DetailPipeline : IPipeline
    {
        private string path;
        public DetailPipeline(string _path)
        {
            
            if (string.IsNullOrEmpty(_path))
            {
                throw new Exception("路徑不能為空!");
            }
            path = _path;
            if (!Directory.Exists(_path))
            {
                Directory.CreateDirectory(_path);
            }
        }
        public void Dispose()
        {
            
        }

        public void Process(ResultItems resultItems, ISpider spider)
        {
            Cnblog cnblog=resultItems.Results["detail"];
            FileStream fs=File.Create(path + "\\" + cnblog.Title + ".txt");
            byte[] bytes=UTF8Encoding.UTF8.GetBytes("Url:"+cnblog.Url+Environment.NewLine+cnblog.Conter);
            fs.Write(bytes,0,bytes.Length);
            fs.Flush();
            fs.Close();
        }
    }

  

修改ListPipeline這個類RequestDetail方法,我的想法是列表數據保存一次就請求一次詳細頁,然後再保存詳細頁

所有詳細頁都保存在details這個目錄下

public class ListPipeline : IPipeline
    {
        private string _path;

        public ListPipeline(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new Exception("文件名不能為空!");
            }

            _path = path;

            if (!File.Exists(_path))
            {
                File.Create(_path);
            }
        }
        public void Dispose()
        {
        }

        public void Process(ResultItems resultItems, ISpider spider)
        {
            lock (this)
            {
                foreach (Cnblog entry in resultItems.Results["Result"])
                {
                    File.AppendAllText(_path, JsonConvert.SerializeObject(entry));
                    RequestDetail(entry);
                }
            }
        }

        /// <summary>
        /// 請求詳細頁
        /// </summary>
        /// <param name="entry"></param>
        private static void RequestDetail(Cnblog entry)
        {
            ISpider spider;
            var site = new Site() {EncodingName = "UTF-8"};
            site.AddStartUrl(entry.Url);
            spider =
                Spider.Create(site, new PageDetailProcessor(entry), new QueueDuplicateRemovedScheduler())
                    .AddPipeline(new DetailPipeline("details"))
                    .SetThreadNum(1);
            spider.Run();
        }
    }

  

其它代碼保持不變,運行程式,現在已經能保存詳細頁內容了

 

最後,程式運行下來沒什麼大問題,但就是在採集詳細頁時比較慢,我的想法是把所有詳細頁一起加到調度中心,然後開多個線程去運行,這個有待學習。 

 

今天把上面的問題解決了,修改ListPipeline類,這樣就可一次把所有詳細頁都加到調度中心,然後開多個線程去請求。

public void Process(ResultItems resultItems, ISpider spider)
        {
            lock (this)
            {
                var site = new Site() { EncodingName = "UTF-8" };
                foreach (Cnblog entry in resultItems.Results["Result"])
                {
                    File.AppendAllText(_path, JsonConvert.SerializeObject(entry));
                    site.AddStartUrl(entry.Url);
                }
                RequestDetail(site);
            }
        }

        /// <summary>
        /// 請求詳細頁
        /// </summary>
        /// <param name="site"></param>
        private static void RequestDetail(Site site)
        {
            ISpider spider =
                Spider.Create(site, new PageDetailProcessor(), new QueueDuplicateRemovedScheduler())
                    .AddPipeline(new DetailPipeline("details"))
                    .SetThreadNum(3);
            spider.Run();
        }

  

 PageDetailProcessor類也更改了,加入標題、url獲取

public void Process(Page page)
        {
            Cnblog cnblog=new Cnblog();
            cnblog.Title = page.Selectable.Select(Selectors.XPath("//a[@id='cb_post_title_url']")).GetValue();
            cnblog.Conter=page.Selectable.Select(Selectors.XPath("//*[@id='cnblogs_post_body']")).GetValue();
            cnblog.Url = page.Url;
            page.AddResultItem("detail",cnblog);
        }

  

 

Demo下載


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、查看Linux內核版本命令(兩種方法): 1、cat /proc/version [root@S-CentOS home]# cat /proc/versionLinux version 2.6.32-431.el6.x86_64 ([email protected]. ...
  • WIN 下的超動態菜單(一)介紹 作者:黃山松,發表於博客園:http://www.cnblogs.com/tomview/ WINDOWS 編程中,通常彈出菜單的方法是在資源文件中建立菜單資源,然後在程式中裝載資源顯示菜單;另外可以用動態創建菜單的方法,但是逐次調用創建菜單添加菜單項的函數很麻煩。... ...
  • 開發板上安裝嵌入式系統要比手機上簡潔很多,有很多擴展的介面,適合對程式進行測試,這裡所提及的是S3C6410開發板。它是由三星公司推出的一款低功耗/高性價比的RISC處理器。,其中包含強大的硬體加速器,還有集成MFC,還有先進的3D加速器,優化了外部介面。如下圖十OK6410開發板的模型圖,便於理解 ...
  • 一、DDNS簡介 DNS,功能變數名稱系統,是網際網路的一項服務,它作為將功能變數名稱和IP地址相互映射的一個分散式資料庫,能夠使人們更方便的訪問互聯網。 DDNS,動態功能變數名稱系統,是功能變數名稱系統(DNS)中的一種自動更新名稱伺服器內容的技術。在傳統的DNS中,功能變數名稱必須和固定的IP綁定,當IP變化時,必須手動更新IP與功能變數名稱 ...
  • Centos6.6 下載地址:thunder://QUFodHRwOi8vbGludXguemh1YW5neGl0b25nLmNvbTo4MDgvMjAxNTAxL0NlbnRPUy02LjYteDg2XzY0LWJpbi1EVkQxLmlzb1pa 1、首先要下載一個centos的iso鏡像,我是 ...
  • 不廢話,直接上如何利用Asp.NET操作XML文件,並對其屬性進行修改,剛開始的時候,是打算使用JS來控制生成XML文件的,但是最後卻是無法創建文件,讀取文件則沒有使用了 index.aspx 文件 index.aspx.cs文件 Command.cs 文件 UserEdit.aspx UserEd ...
  • 1、var 1、均是聲明動態類型的變數。 2、在編譯階段已經確定類型,在初始化的時候必須提供初始化的值。 3、無法作為方法參數類型,也無法作為返回值類型。 2、dynamic 1、均是聲明動態類型的變數。 2、運行時檢查類型,不存在語法類型,在初始化的時候可以不提供初始化的值。 3、反射時簡化代碼, ...
  • 1、通過Nuget下載CORS安裝包 2、在WebApiConfig.cs文件中註冊CORS 3、在全局文件啟用CORS支持 4、在控制器上添加頭 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...