主要参考的博主博客
起因是一直在网上百度小说的百度网盘各种TXT文件都找不到,于是决定自己爬一个下来看看,要爬取的小说链接如下小说
安装模块
这个会用到两个模块,有两种办法安装模块,第一种是直接命令行到python安装的盘里面,然后用
pip install 模块名
另一种就就是如果是用pycharm的话,直接在Settings那里直接输入模块名下载安装,这里就不一一描述了
原博主代码如下
import re
import urllib.request
#定义一个爬取网络小说的函数
def getNovelContent():
html = urllib.request.urlopen("http://www.quanshuwang.com/book/44/44683").read()
html = html.decode("gbk") #转成该网址的格式
#<li><a href="http://www.quanshuwang.com/book/44/44683/15379609.html" title="引子 穿越的唐家三少,共2744字">引子 穿越的唐家三少</a></li> #参考
reg = r'<li><a href="(.*?)" title=".*?">(.*?)</a></li>' #正则表达的匹配
reg = re.compile(reg) #可添加可不添加,增加效率
urls = re.findall(reg,html)
for url in urls:
#print(url)
chapter_url = url[0] #章节的超链接
chapter_title = url[1] #章节的名字
#print(chapter_title)
chapter_html = urllib.request.urlopen(chapter_url).read() #正文内容源代码
chapter_html = chapter_html.decode("gbk")
chapter_reg = r'</script> .*?<br />(.*?)<script type="text/javascript">'
chapter_reg = re.compile(chapter_reg,re.S)
chapter_content = re.findall(chapter_reg,chapter_html)
for content in chapter_content:
content = content.replace(" ","")
content = content.replace("<br />","")
# print(content)
f = open('{}.txt'.format(chapter_title),'w')
f.write(content)
getNovelContent()
因为我找的小说网站的模块跟超链接格式跟原博主的不太一样,所以做了一些修改。还有就是原博主是每一章一个txt文件,我是修改成所有章节都写到同一个txt文件中,代码如下
import re
import