【Python爬虫】使用python脚本拉取网页指定小说章节

示例代码说明:

在小说网站选定一本小说,将小说每个章节内容存为txt文档,文件标题与小说章节标题一致

复制代码
import requests
from lxml import etree
#一本小说链接
Anovellink = 'https://www.hongxiu.com/book/18899519001291804#Catalog'
#目录页代码
ContentsPageCode = requests.get(Anovellink).text
#目录页
ContentsPage = etree.HTML(ContentsPageCode)
href = ContentsPage.xpath('//*[@id="j-catalogWrap"]/div[2]/div/ul/li/a/@href')
for link in href:
    #链接地址
    linkaddress = 'https://www.hongxiu.com' + link
    #章节页面代码
    Chapterpagecode=requests.get(linkaddress).text
    #章节页面
    Chapterpage = etree.HTML(Chapterpagecode)
    #文字列表
    Literallist =Chapterpage.xpath('//div[@class="ywskythunderfont"]/p/text()')
    #标题
    title=Chapterpage.xpath('//h1[@class ="j_chapterName"]/text()')[0]
    file =open('E:/novelpython/'+title+ '.txt','w',encoding='utf-8')
    for paragraph in Literallist:
        file.write(paragraph + '\n')
    print(title +' Chapter crawling is complete')
print('The novel pulling is complete')

结果示例:

相关推荐
曲幽4 小时前
FastAPI 身份验证总踩坑?这份 FastAPI Users “避坑指南”请收好
python·fastapi·web·jwt·oauth2·user·authentication
装不满的克莱因瓶5 小时前
掌握 RNN 与 LSTM 模型结构
人工智能·python·rnn·深度学习·神经网络·ai·lstm
何以解忧,唯有..5 小时前
Python包管理工具pip:从入门到精通
开发语言·python·pip
金銀銅鐵5 小时前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf5 小时前
Python 模块与包的导入导出
前端·后端·python
ice8130331816 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib
copyer_xyf6 小时前
Python venv 虚拟环境
前端·后端·python
林爷万福7 小时前
GitHub 开源光谱数据处理项目推荐
python·光纤光谱仪
copyer_xyf7 小时前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python
Full Stack Developme7 小时前
Spring Bean 依赖注入
python·spring·log4j