利用C#实现最基本的小说爬虫示例代码
作者:XinYiBuFang 时间:2023-09-25 15:48:17
前言
作为一个新手,最近在学习C#,自己折腾弄了个简单的小说爬虫,实现了把小说内容爬下来写入txt,还只能爬指定网站。
第一次搞爬虫,涉及到了网络协议,正则表达式,弄得手忙脚乱跑起来效率还差劲,慢慢改吧。下面话不多说了,来一起看看详细的介绍吧。
爬的目标:http://www.166xs.com/xiaoshuo/83/83557/
一、先写HttpWebRequest把网站扒下来
这里有几个坑,大概说下:
第一个就是记得弄个 * 爬网站,第一次忘了弄代理然后ip就被封了。。。。。
第二个就是要判断网页是否压缩,第一次没弄结果各种转码gbk utf都是乱码。后面解压就好了。
/// <summary>
/// 抓取网页并转码
/// </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;
//设置代理属性WebProxy-------------------------------------------------
WebProxy proxy = new WebProxy("111.13.7.120", 80);
//在发起HTTP请求前将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;
}
二、下面就是用正则处理内容了,由于正则表达式不熟悉所以重复动作太多。
1.先获取网页内容
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; //获取列表内容
Regex Regex_List = new Regex(@"(?is)(?<=<dd>).+?(?=</dd>)");
var Result_List = Regex_List.Matches(Result_Menu); //获取列表集合
3.因为章节列表前面有多余的<dd>,所以要剔除
int i = 0; //计数
string Menu_Content = ""; //所有章节
foreach (var x in Result_List)
{
if (i < 4)
{
//前面五个都不是章节列表,所以剔除
}
else
{
Menu_Content += x.ToString();
}
i++;
}
4.然后获取<a>的href和innerHTML,然后遍历访问获得内容和章节名称并处理,然后写入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标签 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, "");//获取内容页
Regex Rege_Content = new Regex(@"(?is)(?<=<p class=""Book_Text"">).+?(?=</p>)");
string Result_Content = Rege_Content.Match(Content_Html).Value; //获取文章内容
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");//写入标题
Write_Content.WriteLine(Screen_Content);//写入内容
}
Write_Content.Dispose();
Write_Content.Close();
MessageBox.Show(Novel_Name+".txt 创建成功!");
System.Diagnostics.Process.Start(Directory.GetCurrentDirectory() + \\Novel\\);
三、小说写入成功
来源:http://www.cnblogs.com/xinyibufang/p/7615400.html
标签:c#,小说网站,爬虫
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C语言二叉树常见操作详解【前序,中序,后序,层次遍历及非递归查找,统计个数,比较,求深度】
2021-09-30 08:41:23
![](https://img.aspxhome.com/file/2023/8/124038_0s.png)
Spring Boot 异步框架的使用详解
2022-11-14 23:10:38
Android入门之实现自定义Adapter
2021-09-30 17:34:10
![](https://img.aspxhome.com/file/2023/3/88673_0s.jpg)
进度条ProgressBar及ProgressDialog(实例)
2021-09-24 01:07:42
java性能优化之编译器版本与平台对应关系
2023-09-04 18:31:48
Android 消息分发使用EventBus的实例详解
2022-12-23 06:28:28
JAVA多线程并发下的单例模式应用
2022-09-15 01:27:31
SpringBoot使用邮箱发送验证码实现注册功能
2022-03-30 10:13:36
Winform项目中TextBox控件DataBindings属性
2023-03-29 15:25:15
![](https://img.aspxhome.com/file/2023/0/86990_0s.jpg)
Android自定义View实现炫酷进度条
2023-09-22 00:16:07
![](https://img.aspxhome.com/file/2023/3/126753_0s.jpg)
一文理解Android系统中强指针的实现
2022-03-11 11:37:02
详解Maven多模块打包遇到的问题解决方法
2022-12-25 13:01:12
![](https://img.aspxhome.com/file/2023/2/72652_0s.png)
java使用influxDB数据库的详细代码
2023-03-04 05:22:27
用JAVA实现单链表,检测字符串是否是回文串
2021-07-20 07:07:45
ViewFlipper实现上下翻滚轮播效果
2023-10-06 08:55:40
Android开发使用RecyclerView添加点击事件实例详解
2022-04-30 14:11:55
Android模拟器对应的电脑快捷键说明
2022-11-09 17:44:07
android实现录屏功能
2022-04-18 05:11:22
C#操作XML文件步骤
2021-11-04 21:51:44
![](https://img.aspxhome.com/file/2023/3/76433_0s.png)
java开发ServiceLoader实现机制及SPI应用
2022-12-24 09:55:05
![](https://img.aspxhome.com/file/2023/8/69728_0s.png)