Python爬取小说

爬取小说大致分三步

1.获取网页

2.分析获取内容

3.保存到文本

具体步骤放代码里了,注释很清晰了。

python 复制代码
# 爬取小说

#requests是一个常用的 HTTP 请求库,可以方便地向网站发送 HTTP 请求,并获取响应结果。
#pip install requests
#lxml是python的一个解析库,支持HTML和XML的解析,支持XPath解析方式
#pip install lxml
from lxml import etree
import requests
#网站地址
url = "https://dldl1.nsbuket.cc/xiaoshuo/douluodalu/1.html"
while True:
    #伪装用户
    headers={
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0'
    }
    # 发送请求,get方式
    resp = requests.get(url,headers=headers)
    #设置编码
    resp.encoding='utf-8'
    #响应信息
    # print(resp.text)

    # 获取文本
    e=etree.HTML(resp.text)
    info='\n'.join(e.xpath('//div[@class="m-post"]/p/text()'))#章节内容
    title=e.xpath('//h1/text()')[0]#章节标题
    # print(title)
    # print(info)

    # 获取下一章节地址
    url = f'https://dldl1.nsbuket.cc{e.xpath("//td[2]/a/@href")[0]}'
    print(title)

    #保存
    with open('斗罗大陆.txt','a',encoding='utf-8') as f:
        f.write(title+'\n\n'+info+'\n\n')

    #退出循环
    if url=='https://dldl1.nsbuket.cc/xiaoshuo/douluodalu/217333.html':
        break
相关推荐
花酒锄作田14 小时前
Pydantic校验配置文件
python
hboot14 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉
韩师傅2 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L2 天前
LangGraph的MessageState and HumanMessage
python