Python 爬取唐诗三百首:获取王姓诗人作品
你可以使用 Python 的 requests 库和 BeautifulSoup 库来实现网页爬取和数据提取的功能。以下是一个示例代码:
import requests
from bs4 import BeautifulSoup
# 发送 GET 请求获取网页内容
url = 'https://so.gushiwen.org/gushi/tangshi.aspx'
response = requests.get(url)
html = response.text
# 使用 BeautifulSoup 解析网页内容
soup = BeautifulSoup(html, 'html.parser')
# 筛选王姓诗人的诗
poems = soup.find_all('div', class_='cont')
# 提取诗类型、诗名和作者名,并进行编号
count = 1
for poem in poems:
author = poem.find('p', class_='source').find('a').text
if author.startswith('王'):
type_ = poem.find('p', class_='tag').find('a').text
title = poem.find('b').text
print(f'第{count}首 类别:{type_} 诗名:{title} 作者:{author}')
count += 1
运行这段代码,即可输出所有王姓诗人的诗的信息,每首诗都按照要求进行了编号并按照格式进行显示。
原文地址: https://www.cveoy.top/t/topic/o5nR 著作权归作者所有。请勿转载和采集!