【演習14】小説を登ろう〜

主に正規表現を使用して、必要なコンテンツを取得します

import re
import requests
import xlwt  # 加载excel的读取模块

url = 'https://www.xs4.cc/18_9999/'  # 选取了全书网中id为18_9999的小说
req = requests.get(url)  #发起get请求
req.encoding = 'gbk'

# 1、获取书名及作者
novel_name = re.findall('<h1>(.*?)</h1>', req.text)[0]  # 获取书名,其中:req.text:网页内容
novel_author = re.findall('者:(.*?)</p>', req.text)[0]
print(f'小说:《{novel_name}》')
print(f'作者:{novel_author}')


# 2、获取小说章节
novel_chapterTempName = re.findall('html">(.*?)</a>', req.text, re.S)  # 返回章节,此时包含了多余的最新的九个章节、不是小说正文的篇章(一般是作者给读者写的小说外的内容)
novel_chapterName = []  # 记录小说全部章节
#去掉多余的章节
for one in novel_chapterTempName[9:]:
    if re.findall('^第', one):
        novel_chapterName.append(one)
        print(one)  


# 3、获取小说章节网址
novel_chapterId = re.findall('/(.*?).html">第', req.text)  # 返回章节id,此时用‘第’剔除掉了无关的章节
novel_chapterUrl = []   # 记录小说全部章节网址
#去掉多余的最新的章节
for one in novel_chapterId[9:]:
    novel_chapterUrl.append(f'https://www.xs4.cc/{one}.html')
    print(f'https://www.xs4.cc/{one}.html')  


# 4、整合章节、网址到excel表中
# a-利用字典,将章节名、章节网址作为键值对存入字典
novel_dict = {
    
    }
for i in range(len(novel_chapterName)):
    novel_dict[novel_chapterName[i]] = novel_chapterUrl[i]
    
# b-将章节及网址写入excel
novel_excle = xlwt.Workbook()  # 实例化一个excel
novel_sheet = novel_excle.add_sheet(f'{novel_name}')  #新增一个sheet
novel_sheet.write(0, 0, '章节名称')  #0行0列,固定标题:章节名称
novel_sheet.write(0, 1, '章节地址')  #0行1列,固定标题:章节地址

row = 1  #用来每次循环写入一行
for k, v in novel_dict.items():
    novel_sheet.write(row, 0, k)  #在row行的0列写入字典中的key值:章节名
    novel_sheet.write(row, 1, v)  #在row行的0列写入字典中的value值:章节网址
    row += 1
novel_excle.save(f'D:/{novel_name}.xls')    # 以小说名字命名并保存excel


# 5、获取小说前五章的正文
i = 0  #用来取章节列表中的章节名称
for one in novel_chapterUrl[:5]:   #只遍历前五个章节地址
    novel_req = requests.get(one)
    novel_req.encoding = 'gbk'
    novel_body = re.findall('<div id="content">(.*?)</div>',novel_req.text,re.S)  #获取章节正文
    with open(f'D:/{novel_name}-{novel_chapterName[i]}.txt', 'a+') as file_novle:
        file_novle.write(f'{novel_chapterName[i]}\n')  # 文件中第一行写入文字名称
        file_novle.write(str(novel_body).replace("['",'').replace("']",'').replace('&nbsp;',' ').replace('<br />\\r\\n','\n'))  # 对章节正文进行格式化,并写入文件
        i+=1

アクセサリ-結果を印刷します:
1、タイトルと著者
ここに画像の説明を挿入
を取得2、小説の第
ここに画像の説明を挿入
3章を取得するには、セクションURLは小説
ここに画像の説明を挿入
4を取得し、統合章のURLは表
ここに画像の説明を挿入
5を上回り、小説の5つの章を取得します
ここに画像の説明を挿入
ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/weixin_45128456/article/details/112341814