Python爬虫抓取唐诗宋词

时间:2022-07-24
本文章向大家介绍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首代码结束
##################