一个简单爬虫案例,用正则采集小说网站

使用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() 方法进行过滤。

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值