Python 批量爬取古诗文网完整古诗内容
使用 Python 的网络爬虫库 BeautifulSoup 和 requests 可以轻松地从古诗文网批量获取完整古诗内容。
首先,你需要安装以下库:
pip install beautifulsoup4
pip install requests
接下来,你可以使用以下代码来批量获取古诗文网的完整古诗:
import requests
from bs4 import BeautifulSoup
# 定义要爬取的古诗文网页链接
url = 'https://www.gushiwen.cn/'
# 发送请求获取网页内容
response = requests.get(url)
html = response.text
# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(html, 'html.parser')
# 找到所有古诗的链接
poem_links = soup.select('.sons .cont a')
# 遍历每个古诗的链接
for link in poem_links:
# 获取古诗的链接
poem_url = 'https://www.gushiwen.cn' + link['href']
# 发送请求获取古诗的网页内容
poem_response = requests.get(poem_url)
poem_html = poem_response.text
# 使用BeautifulSoup解析古诗的网页内容
poem_soup = BeautifulSoup(poem_html, 'html.parser')
# 找到古诗的标题和内容
title = poem_soup.select_one('.cont h1').text
content = poem_soup.select_one('.cont .contson').text
# 打印古诗的标题和内容
print('标题:', title)
print('内容:', content)
print('------------')
这段代码首先获取古诗文网的首页内容,然后使用 BeautifulSoup 解析网页内容。接着,它会找到首页中所有古诗的链接,并遍历每个链接。对于每个链接,它会发送请求获取古诗的网页内容,并使用 BeautifulSoup 解析古诗的标题和内容。最后,它会打印出每个古诗的标题和内容。
请注意,这段代码只会获取古诗文网首页中的古诗。如果你想获取更多古诗,你可以修改代码来获取其他页面的古诗链接,然后再进行爬取。
原文地址: https://www.cveoy.top/t/topic/mwdg 著作权归作者所有。请勿转载和采集!