【Python脚本】爬取网络小说

原文链接:https://www.cnblogs.com/aksoam/p/18378309

作为重度小说爱好者, 小说下载网站经常被打击,比如:笔趣阁,奇书网,爱书网,80电子书.这些网站的下载链接经常会失效, 所以, 我想自己动手写一个爬虫程序, 抓取网络小说, 并下载到本地.

给出两种思路的python脚本,脚本并不对所有小说网站通用,具体使用时,需要根据网站的网页结构进行修改.

  • 思路1: 给定小说目录页URL,解析所有章节的url,然后遍历,下载每一章的内容,保存到本地文件.
python 复制代码
# -*- coding: utf-8 -*-
"""
方法:
给定小说目录页URL,解析所有章节的url,然后遍历,下载每一章的内容,保存到本地文件.
"""

# 使用requests库发送HTTP请求,获取网页内容
from icecream import ic
import requests
from bs4 import BeautifulSoup
import time
agent={'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0'}
Web_URL = 'https://www.bqzw789.org'  # 笔趣网小说网址
url = 'https://www.bqzw789.org/546/546317/'  # 小说页面URL
txtfile='test.txt'  # 保存小说内容的文件名

response = requests.get(url,headers=agent)
ic(response.status_code)  # 打印响应状态码

with open('test.html', 'wb') as f:  # 保存网页内容到本地文件
    f.write(response.content)

# 解析网页内容
html=response.text
soup = BeautifulSoup(html, 'html.parser')

# 查找章节标题和链接的标签
chapters_link= soup.find_all('a', id='list',href=True)  #<dd><a id="list" href="/546/546317/172937678.html">第六章 炼器师</a></dd>

# 写入到文件
i,k=0,0  # 下载前10章
with open(txtfile, 'w', encoding='utf-8') as f:
    for chapter in chapters_link:
        chap_link=Web_URL+chapter['href']
        resp=requests.get(chap_link,headers=agent)
        
        print(f"正在下载章节: {chapter.text},{chap_link}...")        
        soup2 = BeautifulSoup(resp.text, 'html.parser')
        chapContent= soup2.find('div', id='content')  #<dd><a id="list" href="/546/546317/172937678.html">第六章 炼器师</a></dd>
        # 写入到文件
        # 章节标题
        f.write('\n\n'+chapter.text+'\n\n')
        # 章节内容
        f.write(chapContent.text.replace('\xa0\xa0\xa0\xa0','\n\n'))
  • 思路2: 给定小说的第一章的网站,解析网页中'下一章','下一页'按钮的链接,下载小说的全部章节内容并保存到txt文件中.
python 复制代码
# -*- coding: utf-8 -*-
"""
给定小说的第一章的网站,解析网页中'下一章','下一页'按钮的链接,下载小说的全部章节内容并保存到txt文件中.
"""
# %%
from icecream import ic
import requests
from bs4 import BeautifulSoup
import time

# 预设参数
# 章节名称 标签,class: <h1 class="title">第4章 剧情的开始</h1>
chapter_name_html={'tag':'h1','class':'title'}
# 章节内容 标签,class: <div id="content">...</div>
chapter_content_html={'tag':'div','id':'content','class':'content'}
# 下一页的按钮的文字<a id="next_url" href="/biqu74473/36803977_2.html"> 下一页</a>
next_Page_html={'tag':'a','id':'next_url','text':'下一页'}
# 下一章的按钮的文字  <a id="next_url" href="/biqu74473/36803977.html">下一章 </a>
next_chapter_html={'tag':'a','id':'next_url','text':'下一章'}  

# 脚本参数
# 网址首页
web_url='https://www.22biqu.com'
# 小说第一章的网址
start_url='/biqu74473/36803973.html'
# 请求头
agent={'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0'}
# 保存文件名
txtfile='t1.txt'
# 是否测试?
is_test=False
StatusCodeOK=200
is_write_title=False
end=1 if is_test else 1e6

# 程序执行
fp=open(txtfile,'w',encoding='utf-8')
# 如果处于测试模式,只下载一章内容

i=0
while i<end:
    time.sleep(4)
    # 测试脚本时,只下载第一章内容
    p1=requests.get(web_url+start_url,headers=agent)
    if p1.status_code!=StatusCodeOK:
        fp.write(f"\n请求失败,状态码:{p1.status_code}\n")
        continue
    print(f"正在下载章节{i+1}...,状态码:{p1.status_code}")

    # 解析网页内容
    s1=BeautifulSoup(p1.text,'html.parser')

    # 章节名称
    if is_write_title:
        chap_name=s1.find(chapter_name_html['tag'],class_=chapter_name_html['class']).text
        print(f"章节名称:{chap_name}")
        fp.write(chap_name+'\n\n')

    chap_content=s1.find(chapter_content_html['tag'],id=chapter_content_html['id'])
    fp.write(chap_content.text.replace('\r' , '\n\n'))

    if next_Page_html['text'] in s1.text:
        # print("存在下一页按钮")
        next_url=s1.find(next_Page_html['tag'],id=next_Page_html['id'])['href']
        start_url=next_url
        # print(f"下一页链接:{web_url+next_url}")
    elif next_chapter_html['text'] in s1.text:
        # print("存在下一章按钮")
        next_url=s1.find(next_chapter_html['tag'],id=next_chapter_html['id'])['href']
        start_url=next_url
        # 计数器加1
        i+=1
        # print(f"下一章链接:{web_url+next_url}")
    else:
        # print("没有下一页或章按钮")
        break

print(f"下载完成,文件名:{txtfile},总章节数:{i}")
fp.close()
相关推荐
不会C语言的男孩3 分钟前
C++ Primer 第2章:变量和基本类型
开发语言·c++
lpd_lt16 分钟前
AI Coding的常用Prompt技巧
python·ai·ai编程
小江的记录本18 分钟前
【JVM虚拟机】堆内存分代模型:年轻代(Eden+Survivor)、老年代、元空间Metaspace(附《思维导图》+《面试高频考点清单》)
java·前端·jvm·后端·python·spring·面试
在繁华处22 分钟前
Java从零到熟练(三):流程控制
java·开发语言·python
asdzx671 小时前
使用 Python 快速提取 PDF 中的表格
python·pdf
无情的西瓜皮1 小时前
MCP协议实战:用Python从零搭建一个AI Agent工具服务器(保姆级教程)
服务器·人工智能·python·mcp
云泽8081 小时前
C++ 可调用对象通关指南:深度解析 Lambda 表达式、function 包装器与 bind 绑定器
开发语言·c++·算法
岁月宁静2 小时前
驾驭 AI 这匹野马:深入解析智能体 Harness 工程
vue.js·python
星恒随风3 小时前
Python 基础语法详解(一):从表达式、变量到数据类型
开发语言·笔记·python·学习
888CC++3 小时前
java 并发编程
java·开发语言·python