您的位置:首页 > 科技 > IT业 > 【Python脚本】爬取网络小说

【Python脚本】爬取网络小说

2024/9/24 17:04:26 来源:https://blog.csdn.net/weixin_46037068/article/details/141505981  浏览:    关键词:【Python脚本】爬取网络小说

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

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

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

  • 思路1: 给定小说目录页URL,解析所有章节的url,然后遍历,下载每一章的内容,保存到本地文件.
# -*- 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文件中.
# -*- 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")continueprint(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']).textprint(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# 计数器加1i+=1# print(f"下一章链接:{web_url+next_url}")else:# print("没有下一页或章按钮")breakprint(f"下载完成,文件名:{txtfile},总章节数:{i}")
fp.close()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com