前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python爬虫抓取唐诗宋词

Python爬虫抓取唐诗宋词

作者头像
马一特
发布2020-09-08 11:22:39
5620
发布2020-09-08 11:22:39
举报
文章被收录于专栏:马一特马一特

一 说明

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

二 实操

代码语言:javascript
复制
#!/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首代码结束
##################
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-07-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一 说明
  • 二 实操
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档