【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()
相关推荐
加油,旭杏1 分钟前
【go语言】grpc 快速入门
开发语言·后端·golang
行路见知5 分钟前
1.4 Go 数组
开发语言
2501_9032386512 分钟前
Java 9模块开发:Eclipse实战指南
java·开发语言·eclipse·个人开发
ahardstone13 分钟前
【CS61A 2024秋】Python入门课,全过程记录P5(Week8 Inheritance开始,更新于2025/2/2)
开发语言·python
阿豪学编程28 分钟前
c++ string类 +底层模拟实现
开发语言·c++
MoRanzhi120340 分钟前
亲和传播聚类算法应用(Affinity Propagation)
人工智能·python·机器学习·数学建模·scikit-learn·聚类
金融OG41 分钟前
99.23 金融难点通俗解释:小卖部经营比喻PPI(生产者物价指数)vsCPI(消费者物价指数)
人工智能·python·机器学习·数学建模·金融·数据可视化
是Dream呀1 小时前
Python从0到100(八十六):神经网络-ShuffleNet通道混合轻量级网络的深入介绍
网络·python·神经网络
zxfeng~1 小时前
深度学习之“线性代数”
人工智能·python·深度学习·线性代数
沈韶珺2 小时前
Visual Basic语言的云计算
开发语言·后端·golang