从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(' ','').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'])