【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()
相关推荐
liwulin05067 分钟前
java-在ANTLR中BaseListner的方法和词法规则的关系0.5.0
java·开发语言
梦里花乡15 分钟前
Matlab 的.m 文件批量转成py文件
开发语言·matlab
归去来兮★27 分钟前
c++面向对象
java·开发语言·c++
Aimyon_3627 分钟前
DockerFile
java·开发语言
疑惑的杰瑞38 分钟前
[C语言]连子棋游戏
c语言·开发语言·游戏
wrx繁星点点38 分钟前
创建型模式-单例模式
java·开发语言·单例模式
杨~friendship1 小时前
Ubuntu上使用qt和opencv显示图像
linux·开发语言·c++·qt·opencv·ubuntu
街 三 仔1 小时前
【C语言零基础入门篇 - 3】:格式化输入输出、字符操作和sizeof运算符揭秘
c语言·开发语言
喜欢猪猪1 小时前
TCP/IP网络编程概念及Java实现TCP/IP通讯Demo
开发语言·php
西农小陈1 小时前
python-字符排列问题
数据结构·python·算法