前言:本次爬取的是全书网的某一本小说并以.TXT格式下载到本地。
工具:python3 和 pycharm
Python库:urllib.request 和 re
注意:python是用3以上的版本,库可以在Windows命令提示符里输入pip install+库名
第一步:分析网页
1.首先我们要了解要爬取网站的页面,查看网页源代码。
2.其次要想好代码的步骤和思路。
#获取主页面源代码
#获取章节超链接
#获取小说内容
#下载小说
(全书网某本小说界面)
第二步:开始编程
1.定义库。
import urllib.requestimport re2.定义一个函数egtNovlContent()。
#获取主页面源代码
html = urllib.request.urlopen("http://www.quanshuwang.com/book/9/9055").read()#解码
html = html.decode("gbk")#获取章节超链接
urls = re.findall(req, html)#遍历每章(章节网址和名字)
for i in urls: novel_url = i[0] novel_name = i[1] chapt = urllib.request.urlopen(novel_url).read() chapt_html = chapt.decode("gbk")#获取小说内容
reg = '</script> (.*?)<script type="text/javascript">'#多行匹配
reg = re.compile(reg, re.S) chapt_content = re.findall(reg, chapt_html)#删掉多余的字符串(替换) chapt_content = chapt_content[0].replace(" ","") chapt_content = chapt_content.replace("<br />", "")#下载小说 print("正在下载:%s"%novel_name) f = open('{}.txt'.format(novel_name),"w") f.write(chapt_content) f.close()#调用函数getNovelContent()第三步:运行实践

(pycharm运行)

(本地查看,爬取成功)
源代码如下:


结束语:第一次写博客,写的很糙,望包含,我是初学者,菜鸟一枚,多多学习。
——sum
本文介绍使用Python爬取全书网小说的方法,通过解析网页源代码获取小说章节链接及内容,并以TXT格式保存。
1553





