python项目练习-1

获取无忧书城的小说内容!

python 复制代码
import requests  # 导入请求包
from lxml import etree  # 导入处理xml数据包

url = 'https://www.51shucheng.net/wangluo/douluodalu/21750.html'
book_num = 1  # 文章页数
download_urls = []  # 定义一个空列表,表示我们下载过小说的url!

while True:
    # UA头
    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'}

    resp = requests.get(url, headers=headers)  # 使用get方式请求数据!

    resp.encoding = 'utf-8'  # 将请求的数据编码为 utf-8的格式

    e = etree.HTML(resp.text)  # 使用etree模块处理数据,并赋值给e对象!
    data = ''.join(e.xpath('string(//div[@class="neirong"]/p)'))  # 使用xpath插件获取我需要的标签内容!
    title = e.xpath('//h1/text()')[0]  # 获取文章的标题

    if url in download_urls:
        print(f"跳过重复下载的章节: {title}")
    else:
        filename = f'output/斗罗大陆-第{book_num}章.txt'
        with open(filename, mode='w', encoding='utf-8') as file:
            file.write(title + "\n" + data)
        book_num += 1
        download_urls.append(url)  # 将已经下载章节的url添加到列表中!

    next_url = e.xpath('//div[@class="next"]/a/@href')[0]  # 使用xpath插件获取下一章节url在html标签内的位置!
    if not next_url:
        break
    url = next_url

不会用xpath的话,看下边!

比如我要获取每章节的标题在xml数据中的位置,请看如下图~

相关推荐
Dxy123931021615 分钟前
Python生成随机手机号码
开发语言·python
小帅学编程25 分钟前
Python学习
开发语言·python·学习
两万五千个小时33 分钟前
构建mini Claude Code:08 - Fire and Forget:用后台线程解锁 Multi-Agent 并行执行
人工智能·python·架构
JaydenAI43 分钟前
[拆解LangChain执行引擎]支持自然语言查询的长期存储
python·langchain
dreams_dream1 小时前
Python 的 GIL 是什么?有什么影响?
开发语言·python
小白菜又菜1 小时前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
python·算法·leetcode
多恩Stone1 小时前
【3D-AICG 系列-12】Trellis 2 的 Shape VAE 的设计细节 Sparse Residual Autoencoding Layer
人工智能·python·算法·3d·aigc
Loo国昌2 小时前
【AI应用开发实战】09_Prompt工程与模板管理:构建可演进的LLM交互层
大数据·人工智能·后端·python·自然语言处理·prompt
遨游xyz2 小时前
Trie树(字典树)
开发语言·python·mysql
重启编程之路2 小时前
AlphaLens Pro V14.0 商业级量化推演终端 | 功能白皮书
python