使用Python抓取xx阁小说需要用到 requests 库和正则表达式模块 re,下面是一个具体的实现步骤:

1. 首先需要使用 requests 库请求小说的页面,例如:

import requests

url = 'https://www.biquge.com.cn/book/123456/'
response = requests.get(url)
response.encoding = 'utf-8'

在请求后需注意设置编码,否则可能会出现乱码。

2. 获取小说的标题,可以使用正则表达式模块中的 re.findall() 方法,例如:

import re

title_pattern = re.compile(r'<meta property="og:title" content="(.*?)"/>')
title = title_pattern.findall(response.text)[0]

此处需要用到正则表达式中的捕获组,用来匹配页面上的标题信息。

3. 获取小说的章节列表,也可以使用正则表达式模块中的 re.findall() 方法,例如:

chapter_pattern = re.compile(r'<dd><a href="(.*?)">(.*?)</a></dd>')
chapter_list = chapter_pattern.findall(response.text)

此处的正则表达式用来匹配页面上的章节链接和章节标题信息。

4. 获取每个章节的内容,需要遍历章节列表,并使用同样的方式请求每一个章节的页面并提取相应的内容,例如:

content_pattern = re.compile(r'<div id="content">(.*?)</div>', re.S)
for chapter in chapter_list:
    chapter_url = url + chapter[0]
    chapter_title = chapter[1]
    chapter_response = requests.get(chapter_url)
    chapter_response.encoding = 'utf-8'
    chapter_content = content_pattern.findall(chapter_response.text)[0]
    # 过滤掉内容中的一些无用标签和空格
    chapter_content = chapter_content.replace('&nbsp;', ' ')
    chapter_content = chapter_content.replace('<br/>', '\n')
    chapter_content = chapter_content.replace('<br />', '\n')
    chapter_content = chapter_content.replace('<p>', '')
    chapter_content = chapter_content.replace('</p>', '')
    with open(title + '.txt', 'a', encoding='utf-8') as f:
        f.write(chapter_title + '\n\n' + chapter_content + '\n\n')

此处需要注意的是,章节的内容中可能包含一些无用标签和空格,需要使用字符串的 replace() 方法进行过滤。

在使用正则表达式进行匹配时,还需要注意一些细节,例如正则表达式的贪婪匹配、非贪婪匹配、转义字符等问题。需要仔细阅读官方文档,并进行实际操作和不断调试,才能够熟练掌握正则表达式的使用方法。

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐