前提准备
1、Python环境
2、熟悉使用正则表达式
网页分析
第一步:获取网页源代码,正则表达式匹配链接和标题。处理字符。
第二步,获取每个章节的题目和链接,并打开,采用正则表达式匹配小说内容
代码实战
# coding=utf-8
import urllib.request
import re
#驼峰命名、获取小说内容
def getNoverContent():
#获取网页源代码
html=urllib.request.urlopen("http://www.quanshuwang.com/book/2/2131").read()
#处理字符
html=html.decode("gbk")
#正则匹配,分组匹配
reg=r'<a href="(.*?)" title=".*?">(.*?)</a></li>'
#增加效率
reg=re.compile(reg)
#查找所有
urls=re.findall(reg,html)
#元组
for url in urls:
#获取章节链接并打开
novel_url=url[0]
novel_title=url[1]
chapt=urllib.request.urlopen(novel_url).read()
chapt_html=chapt.decode("gbk")
#print(chapt_html)
#正则表达式获取文章内容
reg=r'</script> (.*?)<script type="text/javascript">'
#匹配换行,S多行匹配
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_title)
#保存为txt文件
f=open('{}.txt'.format(novel_title),'w')
f.write(chapt_content)
#with open('C:/Users/ASUS/Desktop/12.txt','a',encoding='utf-8') as f:
#f.write(chapt_content)
#f.close()
print("爬取完成")
getNoverContent()