【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()
相关推荐
饮水桶_T2 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
炸膛坦客2 小时前
单片机/C/C++八股:(三十四)C 语言函数参数入栈顺序
c语言·开发语言·c++
databook2 小时前
时间序列预测,模型换了一圈为什么没变好
python·数据分析
reasonsummer2 小时前
【教学类-07-17】20261119大3班破译电话号码HTML实际操作(添加“跳过按钮”和“返回按钮”在底部、增加“自编题目+解题”部分)
python·html
咖啡八杯3 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依
bufengwangluo3 小时前
企业上网行为管理:代理网关部署位置怎么选,策略怎么落
开发语言·php
饮水桶_T5 小时前
HashMap笔记
开发语言·数据结构·笔记
2601_967980116 小时前
Python闭包(Closure)详解
python·作用域·装饰器·函数式编程·闭包
布莱克6056 小时前
Swift 下标(Subscript)详解:从语法到实战
服务器·开发语言·ios·ssh·swift·下标
AI创界者6 小时前
ComfyUI 进阶实战:MiniMax-H3 视频人物脸部替换工作流全解析(对比 Face 5.5 实测与避坑指南)
人工智能·python·aigc