Python爬取全书网小说,免费看小说,,什么是网络爬虫网络爬


技术分享图片

什么是网络爬虫

网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或者蠕虫。

环境:Python3.6+Windows

开发工具:你喜欢用哪个就用哪个,你开心就好!

模块:

1 import urllib.request2 3 import re

技术分享图片

主要思路:

1 获取主页源代码

2 获取章节超链接

3 获取章节超链接源码

4 获取小说内容

5 下载,文件操作

技术分享图片

Python代码了解一下

 1 import urllib.request 2 import re 3 # 1 获取主页源代码 4 # 2 获取章节超链接 5 # 3 获取章节超链接源码 6 # 4 获取小说内容 7 # 5 下载,文件操作 8  9 # 驼峰命名法10 # 获取小说内容11 def getNovertContent():12     # <http.client.HTTPResponse object at 0x000001DFD017F400>13     html = urllib.request.urlopen("http://www.quanshuwang.com/book/0/269").read()14     html = html.decode("gbk")15     # 不加括号  不匹配16     # 正则表达式  .*?  匹配所有17     reg = r‘<li><a href="(.*?)" title=".*?">(.*?)</a></li>‘18     # 增加效率的19     reg = re.compile(reg)20     urls = re.findall(reg,html)21     # print(urls)22     # 列表23     # [(http://www.quanshuwang.com/book/0/269/78850.html,第一章 山边小村),24     # (http://www.quanshuwang.com/book/0/269/78854.html,第二章 青牛镇)]25     for url in urls:26         # 章节的URL地址27         novel_url = url[0]28         # 章节标题29         novel_title = url[1]30 31         chapt = urllib.request.urlopen(novel_url).read()32         chapt_html = chapt.decode("gbk")33         # r 表示原生字符串   \ \\d  r"\d"34         reg = r‘</script>&nbsp;&nbsp;&nbsp;&nbsp;(.*?)<script type="text/javascript">‘35         # S 代表多行匹配36         reg = re.compile(reg,re.S)37         chapt_content = re.findall(reg,chapt_html)38         # print(chapt_content)39         # 列表["&nbsp;&nbsp;&nbsp;&nbsp二愣子睁大着双眼,直直望着茅草和烂泥糊成的<br />"]40 41         # 第一个参数   要替换的字符串   替换后的字符串42         chapt_content = chapt_content[0].replace("&nbsp;&nbsp;&nbsp;&nbsp;","")43         # print(chapt_content)    字符串  二愣子睁大着双眼,直直望着茅草和烂泥糊成的<br />44         chapt_content = chapt_content.replace("<br />","")45 46         print("正在保存 %s"%novel_title)47         # w 读写模式  wb48         # f = open("{}.txt".format(novel_title),‘w‘)49         # f.write(chapt_content)50 51         with open("{}.txt".format(novel_title),‘w‘) as f:52             f.write(chapt_content)53 54         # f.close()55 56 getNovertContent()

运行结果:

技术分享图片

技术分享图片

Python爬取全书网小说,免费看小说

评论关闭