用Python批量获取古诗文网的完整古诗
你可以使用Python的requests库来发送网络请求,并使用BeautifulSoup库来解析HTML页面,从而批量获取古诗文网的完整古诗。
首先,安装必要的库:
pip install requests
pip install beautifulsoup4
然后,可以使用以下代码来批量获取古诗文网的完整古诗:
import requests
from bs4 import BeautifulSoup
# 设置请求头,模拟浏览器访问
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
# 获取古诗文网的首页
url = 'https://www.gushiwen.cn/'
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 获取古诗文网的古诗列表
poems = soup.find_all('div', class_='sons')
# 遍历古诗列表,获取每首古诗的链接,并发送请求获取完整内容
for poem in poems:
link = poem.a['href']
poem_url = url + link
poem_response = requests.get(poem_url, headers=headers)
poem_soup = BeautifulSoup(poem_response.text, 'html.parser')
# 获取古诗的完整内容
content = poem_soup.find('div', class_='contson').text.strip()
# 打印古诗内容
print(content)
print('---')
这段代码会获取古诗文网的首页,并解析出古诗列表。然后,遍历古诗列表,获取每首古诗的链接,并发送请求获取完整内容。最后,打印每首古诗的完整内容。
注意:由于古诗文网的页面结构可能会有变化,以上代码可能需要根据实际情况进行调整。
原文地址: https://www.cveoy.top/t/topic/i6ab 著作权归作者所有。请勿转载和采集!