Fork me on GitHub

Python爬虫抓取唐诗宋词

一 说明

Python语言的爬虫开发相对于其他编程语言是极其高效的,在上一篇文章 爬虫抓取博客园前10页标题带有Python关键字(不区分大小写) 的文章中,我们介绍了使用requests做爬虫开发,它能处理简单 的任务,也是入门爬虫最简单的方式。接下来我们将为大家介绍使用 beautiful soup 库 来做稍微复杂一点的任务。

二 实操

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2020/7/23 5:58 下午
# @Author  : Albert Ma
# @File    : test1.py

import requests
from bs4 import BeautifulSoup

##################
# 唐诗300首代码开始
##################
numbers = []
dynasties = []
poets = []
names = []
poems = []

for i in range(1, 17):
    i = str(i)
    url = 'http://www.shicimingju.com/shicimark/tangshisanbaishou_' + i + '_0__0.html'

    r = requests.get(url)
    demo = r.text  # 服务器返回响应

    soup = BeautifulSoup(demo, "html.parser")
    """
    demo 表示被解析的html格式的内容
    html.parser表示解析用的解析器
    """

    html1 = soup.find_all(class_ = 'list_num_info')
    for text in html1:
        text = text.get_text().replace('\n', '').replace(' ', '').replace('[', '|').replace(']', '|')
        text = text.split('|')
        numbers.append(text[0])
        dynasties.append(text[1])
        poets.append(text[2])

    html2 = soup.find_all(class_ = 'shici_list_main')
    for text in html2:
        text = text.get_text().replace('\n', '').replace(' ', '')
        text = text.replace('展开全文', '').replace('收起', '').replace('《', '').replace('》', '|')
        text = text.split('|')
        names.append(text[0])
        poems.append(text[1])

print(len(names), names)
print(len(poets), poets)

print(len(poems), poems)
print(len(numbers), numbers)
print(len(dynasties), dynasties)

##################
# 唐诗300首代码结束
##################
posted @   马一特  阅读(741)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示

目录