用python爬取笔趣阁小说

# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
from urllib import request
if __name__=='__main__':
    file = open('一念永恒.txt', 'w', encoding='utf-8')
    yinianyonghen_url="http://www.biqukan.com/1_1094/"
    head={}
    head['User-Agent']="Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19"
    yinianyonghen_req=request.Request(url=yinianyonghen_url,headers
### Python 爬虫抓取小说内容教程 #### 准备工作 在开始编写爬虫前,需安装必要的依赖库。主要使用的库有 `requests` 和 `BeautifulSoup`,分别用于发送 HTTP 请求和解析 HTML 页面。 ```bash pip install requests beautifulsoup4 lxml ``` #### 获取网页内容 通过 `requests.get()` 方法访问目标网站并获取其 HTML 内容。需要注意的是,部分网站可能设置了反爬机制,因此可以通过设置请求头 (`headers`) 来模拟浏览器行为[^1]。 ```python import requests url = "https://www.example.com/novel" 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, headers=headers) if response.status_code == 200: html_content = response.text else: print("Failed to retrieve the webpage.") ``` #### 解析网页结构 利用 `BeautifulSoup` 对获取的 HTML 文本进行解析,提取所需的小说章节链接及标题信息[^2]。 ```python from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, 'lxml') chapter_list = soup.find_all('a', class_='chapter-item') chapters = [] for chapter in chapter_list: chapters.append({ "title": chapter.text.strip(), "link": chapter['href'] }) ``` #### 数据存储 定义函数保存每章的数据至本地文件夹中。这里采用 `os.path.join` 构建跨平台兼容路径,并验证目录是否存在以决定是否新建[^3]。 ```python import os def save_chapter(title, content): folder_name = "novel_folder" full_path = os.path.join(os.getcwd(), folder_name) if not os.path.exists(full_path): os.makedirs(full_path) file_path = os.path.join(full_path, f"{title.replace('/', '_')}.txt") with open(file_path, 'w', encoding='utf-8') as f: f.write(content) ``` #### 多线程优化效率 为了提高下载速度,可以引入异步处理方式减少等待时间。下面展示了一个简单的基于同步模式的例子;对于更复杂的场景建议研究 `asyncio` 或者第三方框架如 Scrapy[^4]。 ```python def fetch_and_save(chapter_info): url = chapter_info["link"] resp = requests.get(url, headers=headers) soup = BeautifulSoup(resp.text, 'lxml') text_blocks = soup.select('.content p') content = "\n".join([p.text for p in text_blocks]) save_chapter(chapter_info["title"], content) # 单进程执行 for chap in chapters[:5]: # 只测试前五章作为演示 fetch_and_save(chap) ``` #### 注意事项 - **合法性**:确保遵守目标站点的服务条款以及版权法律。 - **频率控制**:适当降低请求频次以免给服务器带来过大压力甚至被封禁 IP 地址。 - **异常捕获**:增加 try-except 块应对可能出现的各种错误情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值