Python爬虫学习2----小说网站爬虫开发

https://www.kanunu8.com/book3/8486抓取《天使国度的恶龙王妃》所有章节的网址,再通过一个多线程爬虫将每章的内容抓去下来。在本地创建一个“《天使国度的恶龙王妃》”的文件夹,并将小说的每一章分别保存到这个文件夹中。

import re
import requests
import os
from multiprocessing import Pool

def get_article_url_list(html):
    top_url = 'https://www.kanunu8.com/book3/8486/'
    all_article_str = re.findall('正文</strong></td>(.*?)</tbody>',html,re.S)[0]
    all_article_url = re.findall('href="(.*?)</a></td>',all_article_str,re.S)

    article_url_list = []
    for article_url in all_article_url:
        tail_url = re.findall('(.*)">',article_url,re.S)[0]
        article_url_list.append(top_url + tail_url)

    return article_url_list

def get_article(article_url):
    article_html = requests.get(article_url).content.decode('GB2312')
    article_topic = re.findall('size="4">(.*?)</font><strong></td>',article_html,re.S)[0].strip()
    article_content = re.findall('<p>(.*?)</p>',article_html,re.S)[0].replace('&nbsp;&nbsp;&nbsp;&nbsp;','').replace('<br />','')
    article_map = {}
    article_map['topic'] = article_topic
    article_map['content'] = article_content
    return article_map

if __name__ == '__main__':
    #获取小说目录的源代码
    html = requests.get('https://www.kanunu8.com/book3/8486/index.html').content.decode('GB2312')
    #获取每章小说的url
    article_url_list = get_article_url_list(html)
    #开启多线程,获取文章标题内容的字典列表
    pool = Pool(5)
    article_map_list = pool.map(get_article,article_url_list)
    # 创建保存小说所有章节的文件夹,exist_ok=True 表示如果文件夹存在就什么都不做
    os.makedirs('E:\\《天使国度的恶龙王妃》', exist_ok=True)
    for article_map in article_map_list:
        #保存某章小说为txt文件,'w' 为覆盖式写入,newline='' 解决空行问题
        with open('E:\\《天使国度的恶龙王妃》\\'+article_map['topic']+'.txt','w',encoding='utf-8',newline='') as f:
            f.write(article_map['content'])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值