使用BeautifulSoup爬取笔趣阁小说

本文演示了如何利用BeautifulSoup爬取笔趣阁上的小说《元尊》,逐步爬取了从第1章到第9章的内容,共597章。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用BeautifulSoup爬取笔趣阁小说


今天下午学习了一下BeautifulSoup,正好本人书荒,于是以笔趣阁网站为研究对象,就写了个爬小说的代码。放上来供大家参考,也请高手指正。
先放代码:

代码

import urllib.request as ur
from bs4 import BeautifulSoup
import ssl
import re


def get_soup(address):
    '''抓取网页,创建BeautifulSoup对象'''
    context = ssl._create_unverified_context()  # 取消验证
    headers = {
    
    'User-Agent': 'Chrome/68.0.3440.84'}
    request = ur.Request(address, headers=headers)
    response = ur.urlopen(request, timeout=20, context=context)
    content = response.read(
### 爬取小说数据的方法 爬取小说的数据可以通过编写一个基于Python的网络爬虫实现。以下是具体方法和技术要点: #### 1. 使用requests库发送HTTP请求 为了访问目标网站并获取HTML页面的内容,可以使用`requests`库来模拟浏览器行为发起GET或POST请求[^2]。 ```python import requests url = 'https://www.xbiquge.la/search.php' params = {'searchkey': '伏天氏'} # 替换为目标小说名称 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } response = requests.get(url, params=params, headers=headers) html_content = response.text ``` #### 2. 解析网页内容 通过`BeautifulSoup`解析返回的HTML文档,提取所需的信息,比如小说章节链接和标题[^1]。 ```python from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, 'lxml') novel_links = soup.find_all('a', class_='result-game-item-title-link') for link in novel_links[:5]: # 取前五个结果作为示例 title = link['title'] href = link['href'] print(f'标题: {title}, 链接: {href}') ``` #### 3. 下载章节内容 进入单个章节页面后,继续抓取正文部分,并保存至本地文件中[^2]。 ```python chapter_url = href # 假设这是某个章节的具体地址 chapter_response = requests.get(chapter_url, headers=headers) if chapter_response.status_code == 200: chapter_soup = BeautifulSoup(chapter_response.text, 'lxml') content_div = chapter_soup.select_one('#content') # 查找实际存储文章的地方 if content_div: text = content_div.get_text().strip() with open('output.txt', mode='w+', encoding='utf-8') as f: f.write(text) else: print("无法加载该章节") ``` #### 4. 文件操作注意事项 当处理含有大量中文字符的情况下,推荐采用`codecs.open()`函数替代普通的`open()`以确保编码正确无误[^2]。 --- ### 提醒事项 需要注意的是,在实施上述过程之前,请务必确认目标站点的服务条款允许此类自动化脚本运行;否则可能违反其规定甚至触犯法律。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值