DotnetSpider爬蟲圖文日記--小說下載(C#,dotnetcore)

項目簡介:

需求:爬取網(wǎng)頁所有的“玄幻”類型小說。

系統(tǒng):Windows10

工具:Visual Studio Code

環(huán)境:.NET Core 2.1

爬蟲庫:DotnetSpider

開始之前:

下載書的部分,用到了Python,因為我不知道如何在C#中操作。謝謝!

一:創(chuàng)建項目

在指定目錄,創(chuàng)建 DotnetCore Console 程序,并使用 VSCode(Visual Studio Code 后面都使用簡稱) 打開此項目。

# 右下角,提示選擇 YES。

添加 DotnetSpider 的庫。點擊:視圖--終端,或者按 CTRL+(TAB上面那個鍵),輸入:dotnet add package DotnetSpider.Core --version 2.6.0-beta5。安裝完成后,會提示,還原項目,點擊。



二:編輯 Program.cs

using System;

using System.Collections.Generic;

using System.IO;

using System.Text.RegularExpressions;

using DotnetSpider.Core;

using DotnetSpider.Core.Downloader;

using DotnetSpider.Core.Pipeline;

using DotnetSpider.Core.Processor;

using DotnetSpider.Core.Scheduler;

using DotnetSpider.Core.Selector;

namespace SpiderFiction

{

? ? class Program

? ? {

? ? ? ? static void Main(string[] args)

? ? ? ? {

? ? ? ? ? ? CostomPageProcessorAndPipeline();

? ? ? ? ? ? Console.WriteLine("下載完畢?。?!按任意鍵退出!??!");

? ? ? ? ? ? Console.Read();

? ? ? ? }

? ? ? ? private static void CostomPageProcessorAndPipeline()

? ? ? ? {

? ? ? ? ? ? // 玄幻小說的首頁網(wǎng)址

? ? ? ? ? ? string url = "http://www.jjxsw.com/e/action/ListInfo.php?page=0&classid=11&line=10&tempid=3&ph=1&andor=and&qujian=4&orderby=2&myorder=0&totalnum=150";

? ? ? ? ? ? Site site = new Site { CycleRetryTimes = 3, SleepTime = 300 };

? ? ? ? ? ? site.AddStartUrl(url);

? ? ? ? ? ? // 使用 PageProcessor和 Scheduler創(chuàng)建一個爬行器。添加數(shù)據(jù)處理管道

? ? ? ? ? ? Spider spider = Spider.Create(site, new QueueDuplicateRemovedScheduler(), new FictionPageProcessor()).AddPipeline(new FictionPipeline());

? ? ? ? ? ? // 爬蟲下載器

? ? ? ? ? ? spider.Downloader = new HttpClientDownloader();

? ? ? ? ? ? // 爬蟲的線程數(shù)

? ? ? ? ? ? spider.ThreadNum = 4;

? ? ? ? ? ? // 當(dāng)沒有其它鏈接請求時,爬蟲的退出時間

? ? ? ? ? ? spider.EmptySleepTime = 2000;

? ? ? ? ? ? // 啟動爬蟲

? ? ? ? ? ? spider.Run();

? ? ? ? }

? ? }

? ? ///

? ? /// 對獲取到的網(wǎng)頁,進行解析,解析到的數(shù)據(jù),將傳到 Pipeline 中,進行處理

? ? ///

? ? internal class FictionPageProcessor:BasePageProcessor

? ? {

? ? ? ? protected override void Handle(Page page)

? ? ? ? {

? ? ? ? ? ? // 獲取當(dāng)前頁面中,所有的小說: 標(biāo)簽的列表

? ? ? ? ? ? var totalFictionElements = page.Selectable.XPath("http://div[@class=\"listbg\"]/a[1]").Nodes();

? ? ? ? ? ? // 創(chuàng)建小說類,列表。

? ? ? ? ? ? List results = new List();

? ? ? ? ? ? string reurl = "";

? ? ? ? ? ? foreach (var fictionElement in totalFictionElements)

? ? ? ? ? ? {

? ? ? ? ? ? ? ? var fiction = new Fiction();

? ? ? ? ? ? ? ? // 得到小說頁面的鏈接

? ? ? ? ? ? ? ? reurl = fictionElement.Select(Selectors.XPath("@href")).GetValue();

? ? ? ? ? ? ? ? // 通過 ReURL 將小說頁面的鏈接,替換為 下載頁面的鏈接

? ? ? ? ? ? ? ? fiction.Url = ReURL(reurl);

? ? ? ? ? ? ? ? results.Add(fiction);

? ? ? ? ? ? }

? ? ? ? ? ? // 小說保存到頁面的結(jié)果中

? ? ? ? ? ? page.AddResultItem("FictionResult", results);

? ? ? ? ? ? // 實現(xiàn)翻面效果,獲取后面的頁面

? ? ? ? ? ? foreach (var url in page.Selectable.XPath("http://div[@class=\"pager\"]/ul").Links().Nodes())

? ? ? ? ? ? {

? ? ? ? ? ? ? ? // 得到的鏈接包含多余的字符,將其替換掉

? ? ? ? ? ? ? ? string u = replace(url.GetValue());

? ? ? ? ? ? ? ? // 將解析到的后續(xù)頁面,添加到目標(biāo)請求中,這將會遍歷所有的頁面

? ? ? ? ? ? ? ? page.AddTargetRequest(new Request(u, null));

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? ///

? ? ? ? /// 替換多余的字符

? ? ? ? ///

? ? ? ? /// 需要修改的字符串

? ? ? ? /// 可以正常訪問的鏈接

? ? ? ? private string replace(string v) => v.Replace("amp;", "");

? ? ? ? ///

? ? ? ? /// 修改 URL

? ? ? ? ///

? ? ? ? /// 小說頁面的 URL 例:http://www.jjxsw.com/txt/26697.htm

? ? ? ? /// 小說下載頁面的 URL 例:http://www.jjxsw.com/txt/dl-11-26697.html

? ? ? ? private string ReURL(string reurl)

? ? ? ? {

? ? ? ? ? ? string url = reurl + "l"; // 獲取到的鏈接少了一個 "L"

? ? ? ? ? ? string pattern = "\\d+";

? ? ? ? ? ? string replace = "dl-11-" + Path.GetFileNameWithoutExtension(url);

? ? ? ? ? ? return Regex.Replace(url, pattern, replace);

? ? ? ? }

? ? }

? ? ///

? ? /// 小說對象

? ? ///

? ? internal class Fiction

? ? {

? ? ? ? ///

? ? ? ? /// 保存小說下載地址的 URL

? ? ? ? ///

? ? ? ? public string Url{get;set;}

? ? }

? ? ///

? ? /// 對 PageProcessor 解析到的頁面數(shù)據(jù),進行處理

? ? ///

? ? internal class FictionPipeline : BasePipeline

? ? {

? ? ? ? ///

? ? ? ? /// 保存所有小說,下載頁面的 URL

? ? ? ? /// 例:例:http://www.jjxsw.com/txt/dl-11-26697.html

? ? ? ? ///

? ? ? ? List urlList = new List();

? ? ? ? public override void Process(IEnumerable resultItems, ISpider spider)

? ? ? ? {

? ? ? ? ? ? foreach (var resultItem in resultItems)

? ? ? ? ? ? {


? ? ? ? ? ? ? ? foreach (Fiction entry in resultItem.Results["FictionResult"])

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? // 所有的小說,下載頁面的 URL

? ? ? ? ? ? ? ? ? ? urlList.Add(entry.Url);

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? ? ? // 下載小說類,得到所有小說的下載鏈接 URL

? ? ? ? ? ? DownFiction df = new DownFiction(urlList);

? ? ? ? ? ? df.Run();

? ? ? ? }

? ? }

}


三:添加 DownFiction 類

using DotnetSpider.Core;

using DotnetSpider.Core.Downloader;

using DotnetSpider.Core.Pipeline;

using DotnetSpider.Core.Processor;

using DotnetSpider.Core.Scheduler;

using System;

using System.Collections.Generic;

using System.IO;

namespace SpiderFiction

{

? ? ///

? ? /// 獲取所有小說的下載鏈接

? ? /// 例如:http://www.jjxsw.com/e/DownSys/doaction.php?enews=DownSoft&classid=11&id=26697&pathid=0&pass=ee247a67a5adcf1dfb1abecbd1ff5635&p=:::

? ? ///

? ? class DownFiction

? ? {

? ? ? ? ///

? ? ? ? /// 小說下載頁面的連接

? ? ? ? /// 例:http://www.jjxsw.com/txt/dl-11-26697.html

? ? ? ? ///

? ? ? ? private List urlList;

? ? ? ? public DownFiction(List urlList)

? ? ? ? {

? ? ? ? ? ? this.urlList = urlList;


? ? ? ? }

? ? ? ? ///

? ? ? ? /// 頁面解析:獲取小說下載連接,并寫入本地文件

? ? ? ? ///

? ? ? ? internal void Run()

? ? ? ? {

? ? ? ? ? ? XpathFiction(urlList);

? ? ? ? ? ? DownFictionPipeline df = new DownFictionPipeline();

? ? ? ? ? ? // 沒有直接下載,而是存入文件,因為我不知道,如何在 C# 中,解析那樣的網(wǎng)址

? ? ? ? ? ? df.WriteToFile();

? ? ? ? }

? ? ? ? ///

? ? ? ? /// 創(chuàng)建站點信息、爬蟲

? ? ? ? ///

? ? ? ? ///

? ? ? ? private void XpathFiction(List urlList)

? ? ? ? {

? ? ? ? ? ? Site site = new Site { CycleRetryTimes = 3, SleepTime = 300 };

? ? ? ? ? ? site.AddStartUrls(urlList);

? ? ? ? ? ? Spider spider = Spider.Create(site, new QueueDuplicateRemovedScheduler(), new DownFictionPageProcessor()).AddPipeline(new DownFictionPipeline());

? ? ? ? ? ? spider.Downloader = new HttpClientDownloader();

? ? ? ? ? ? spider.ThreadNum = 4;

? ? ? ? ? ? spider.EmptySleepTime = 2000;

? ? ? ? ? ? spider.Run();

? ? ? ? }


? ? }

? ? ///

? ? /// 解析數(shù)據(jù)

? ? ///

? ? internal class DownFictionPageProcessor:BasePageProcessor

? ? {

? ? ? ? public DownFictionPageProcessor()

? ? ? ? {

? ? ? ? }

? ? ? ? protected override void Handle(Page page)

? ? ? ? {

? ? ? ? ? ? // 小說的下載鏈接:http://www.jjxsw.com/e/DownSys/doaction.php?enews=DownSoft&classid=11&id=26697&pathid=0&pass=ee247a67a5adcf1dfb1abecbd1ff5635&p=:::

? ? ? ? ? ? page.AddResultItem("url", page.Selectable.XPath("http://a[@class=\"strong green\"][1]/@href").GetValue());

? ? ? ? }

? ? }

? ? internal class DownFictionPipeline : BasePipeline

? ? {

? ? ? ? private static List urls = new List();

? ? ? ? // 本地文本的位置

? ? ? ? private readonly string path = @"D:\ASP.NET Core\Book\URL.txt";

? ? ? ? public override void Process(IEnumerable resultItems, ISpider spider)

? ? ? ? {

? ? ? ? ? ? foreach (var result in resultItems)

? ? ? ? ? ? {

? ? ? ? ? ? ? ? // 將所有的鏈接,保存到 List 中

? ? ? ? ? ? ? ? urls.Add(result.Results["url"] as string);

? ? ? ? ? ? }

? ? ? ? }

? ? ? public void WriteToFile()

? ? ? ? {

? ? ? ? ? ? try

? ? ? ? ? ? {

? ? ? ? ? ? ? ? // 保存所有的鏈接到本地

? ? ? ? ? ? ? ? File.WriteAllLines(path, urls);

? ? ? ? ? ? }

? ? ? ? ? ? catch (Exception ee)

? ? ? ? ? ? {

? ? ? ? ? ? ? ? using (StreamWriter sw = new StreamWriter(@"D:\ASP.NET CORE\Book\log.txt",true))

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? sw.WriteLine(ee.Message);

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? }

? ? }

}


點擊:視圖--終端,或者按 CTRL+(TAB上面那個鍵),輸入:dotnet run,執(zhí)行程序。

程序會將,所有的小說鏈接,下載到本地。

由于我不知道,如何在 C# 中使用這些小說的下載鏈接,所以保存到了本地。

接下來,我將使用 Python ,解析這些鏈接,并下載小說保存到本地。

四:新建一個 Python 文件


文件正在下載,保存。

如果有人看到此文章,并有其它想法,歡迎指教,謝謝。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,525評論 19 139
  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網(wǎng)絡(luò)請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,175評論 3 119
  • 當(dāng)我們用vmvare安裝完成centos6.5的時候,用root用戶登錄發(fā)現(xiàn)無網(wǎng)絡(luò)連接。狀態(tài)如下: 查資料發(fā)現(xiàn)這個...
    我最愛吃大西瓜了閱讀 422評論 0 0
  • 早上出門,準(zhǔn)備趕車去上班。院子外馬路邊,人行道上有一個熟悉的老太太。她是住在我們樓下的鄰居,曾經(jīng)在樓道里面,遇見過...
    阿牛_50f7閱讀 427評論 0 0
  • 【書名】精進,如何成為一個很厲害的人 【作者】采銅 【金句】 知識創(chuàng)造的過程,其實是隱性知識和顯性知識相互轉(zhuǎn)化的過...
    必贏有話說閱讀 608評論 18 9

友情鏈接更多精彩內(nèi)容