利用C#實(shí)現(xiàn)最基本的小說爬蟲示例代碼
前言
作為一個(gè)新手,最近在學(xué)習(xí)C#,自己折騰弄了個(gè)簡單的小說爬蟲,實(shí)現(xiàn)了把小說內(nèi)容爬下來寫入txt,還只能爬指定網(wǎng)站。
第一次搞爬蟲,涉及到了網(wǎng)絡(luò)協(xié)議,正則表達(dá)式,弄得手忙腳亂跑起來效率還差勁,慢慢改吧。下面話不多說了,來一起看看詳細(xì)的介紹吧。
爬的目標(biāo):http://www.166xs.com/xiaoshuo/83/83557/
一、先寫HttpWebRequest把網(wǎng)站扒下來
這里有幾個(gè)坑,大概說下:
第一個(gè)就是記得弄個(gè)代理IP爬網(wǎng)站,第一次忘了弄代理然后ip就被封了。。。。。
第二個(gè)就是要判斷網(wǎng)頁是否壓縮,第一次沒弄結(jié)果各種轉(zhuǎn)碼gbk utf都是亂碼。后面解壓就好了。
/// <summary> /// 抓取網(wǎng)頁并轉(zhuǎn)碼 /// </summary> /// <param name="url"></param> /// <param name="post_parament"></param> /// <returns></returns> public string HttpGet(string url, string post_parament) { string html; HttpWebRequest Web_Request = (HttpWebRequest)WebRequest.Create(url); Web_Request.Timeout = 30000; Web_Request.Method = "GET"; Web_Request.UserAgent = "Mozilla/4.0"; Web_Request.Headers.Add("Accept-Encoding", "gzip, deflate"); //Web_Request.Credentials = CredentialCache.DefaultCredentials; //設(shè)置代理屬性WebProxy------------------------------------------------- WebProxy proxy = new WebProxy("111.13.7.120", 80); //在發(fā)起HTTP請(qǐng)求前將proxy賦值給HttpWebRequest的Proxy屬性 Web_Request.Proxy = proxy; HttpWebResponse Web_Response = (HttpWebResponse)Web_Request.GetResponse(); if (Web_Response.ContentEncoding.ToLower() == "gzip") // 如果使用了GZip則先解壓 { using (Stream Stream_Receive = Web_Response.GetResponseStream()) { using (var Zip_Stream = new GZipStream(Stream_Receive, CompressionMode.Decompress)) { using (StreamReader Stream_Reader = new StreamReader(Zip_Stream, Encoding.Default)) { html = Stream_Reader.ReadToEnd(); } } } } else { using (Stream Stream_Receive = Web_Response.GetResponseStream()) { using (StreamReader Stream_Reader = new StreamReader(Stream_Receive, Encoding.Default)) { html = Stream_Reader.ReadToEnd(); } } } return html; }
二、下面就是用正則處理內(nèi)容了,由于正則表達(dá)式不熟悉所以重復(fù)動(dòng)作太多。
1.先獲取網(wǎng)頁內(nèi)容
IWebHttpRepository webHttpRepository = new WebHttpRepository(); string html = webHttpRepository.HttpGet(Url_Txt.Text, "");
2.獲取書名和文章列表
書名
文章列表
string Novel_Name = Regex.Match(html, @"(?<=<h1>)([\S\s]*?)(?=</h1>)").Value; //獲取書名 Regex Regex_Menu = new Regex(@"(?is)(?<=<dl class=""book_list"">).+?(?=</dl>)"); string Result_Menu = Regex_Menu.Match(html).Value; //獲取列表內(nèi)容 Regex Regex_List = new Regex(@"(?is)(?<=<dd>).+?(?=</dd>)"); var Result_List = Regex_List.Matches(Result_Menu); //獲取列表集合
3.因?yàn)檎鹿?jié)列表前面有多余的<dd>,所以要剔除
int i = 0; //計(jì)數(shù) string Menu_Content = ""; //所有章節(jié) foreach (var x in Result_List) { if (i < 4) { //前面五個(gè)都不是章節(jié)列表,所以剔除 } else { Menu_Content += x.ToString(); } i++; }
4.然后獲取<a>的href和innerHTML,然后遍歷訪問獲得內(nèi)容和章節(jié)名稱并處理,然后寫入txt
Regex Regex_Href = new Regex(@"(?is)<a[^>]*?href=(['""]?)(?<url>[^'""\s>]+)\1[^>]*>(?<text>(?:(?!</?a\b).)*)</a>"); MatchCollection Result_Match_List = Regex_Href.Matches(Menu_Content); //獲取href鏈接和a標(biāo)簽 innerHTML string Novel_Path = Directory.GetCurrentDirectory() + "\\Novel\\" + Novel_Name + ".txt"; //小說地址 File.Create(Novel_Path).Close(); StreamWriter Write_Content = new StreamWriter(Novel_Path); foreach (Match Result_Single in Result_Match_List) { string Url_Text = Result_Single.Groups["url"].Value; string Content_Text = Result_Single.Groups["text"].Value; string Content_Html = webHttpRepository.HttpGet(Url_Txt.Text + Url_Text, "");//獲取內(nèi)容頁 Regex Rege_Content = new Regex(@"(?is)(?<=<p class=""Book_Text"">).+?(?=</p>)"); string Result_Content = Rege_Content.Match(Content_Html).Value; //獲取文章內(nèi)容 Regex Regex_Main = new Regex(@"( )(.*)"); string Rsult_Main = Regex_Main.Match(Result_Content).Value; //正文 string Screen_Content = Rsult_Main.Replace(" ", "").Replace("<br />", "\r\n"); Write_Content.WriteLine(Content_Text + "\r\n");//寫入標(biāo)題 Write_Content.WriteLine(Screen_Content);//寫入內(nèi)容 } Write_Content.Dispose(); Write_Content.Close(); MessageBox.Show(Novel_Name+".txt 創(chuàng)建成功!"); System.Diagnostics.Process.Start(Directory.GetCurrentDirectory() + \\Novel\\);
三、小說寫入成功
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
關(guān)于Flyweight模式應(yīng)用實(shí)踐的相關(guān)介紹
本篇文章,小編將為大家介紹Flyweight模式應(yīng)用實(shí)踐,有需要的朋友可以參考一下2013-04-04Unity實(shí)現(xiàn)透視滑動(dòng)列表
這篇文章主要為大家詳細(xì)介紹了Unity實(shí)現(xiàn)透視滑動(dòng)列表,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07C# Form自定義光標(biāo)的簡單實(shí)現(xiàn)
這篇文章主要介紹了C# Form自定義光標(biāo)的簡單實(shí)現(xiàn),有需要的朋友可以參考一下2014-01-01C#中的文件路徑獲取函數(shù)和文件名字獲取函數(shù)小結(jié)
這篇文章主要介紹了C#中的文件路徑獲取函數(shù)和文件名字獲取函數(shù)小結(jié),本文講解了獲取絕對(duì)文件路徑、獲取文件名字、獲得包含 path 目錄信等內(nèi)容,需要的朋友可以參考下2015-01-01BarCode條形碼基于C# GDI+ 的實(shí)現(xiàn)方法詳解
本篇文章介紹了,BarCode條形碼基于C# GDI+ 的實(shí)現(xiàn)方法詳解。需要的朋友參考下2013-05-05C#創(chuàng)建數(shù)據(jù)庫及附加數(shù)據(jù)庫的操作方法
這篇文章主要介紹了C#創(chuàng)建數(shù)據(jù)庫及附加數(shù)據(jù)庫的操作方法,涉及C#針對(duì)數(shù)據(jù)庫常見的創(chuàng)建、添加、連接等操作技巧,需要的朋友可以參考下2016-06-06