Python-正则 爬取全书网小说

前提准备

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>&nbsp;&nbsp;&nbsp;&nbsp;(.*?)<script type="text/javascript">'
        #匹配换行,S多行匹配
        reg=re.compile(reg,re.S)
        chapt_content=re.findall(reg,chapt_html)
        #替换空格
        chapt_content=chapt_content[0].replace("&nbsp;&nbsp;&nbsp;&nbsp;","")
        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()    
 
 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值