Python 批量爬取古诗文网完整古诗内容教程

本教程将使用 Python 的 requests 和 BeautifulSoup 库来批量爬取古诗文网的完整古诗内容,提供详细代码示例和步骤,帮助您轻松获取古诗数据。

1. 安装必要库

首先,使用以下命令安装 requests 和 BeautifulSoup4 库:

pip install requests
pip install beautifulsoup4

2. 代码示例

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('---')

3. 代码说明

  1. 代码首先导入 requests 和 BeautifulSoup 库,并设置请求头,模拟浏览器访问。
  2. 获取古诗文网的首页内容,并使用 BeautifulSoup 解析 HTML 页面。
  3. 找到古诗列表,遍历列表中的每个古诗条目,获取每个古诗的链接。
  4. 针对每个古诗链接,发送请求获取其页面内容,并使用 BeautifulSoup 解析。
  5. 在页面中找到包含古诗内容的 div 元素,提取并打印其文本内容。

4. 注意

由于古诗文网的页面结构可能会有变化,以上代码可能需要根据实际情况进行调整。

5. 扩展

您可以根据自己的需求对代码进行扩展,例如:

  • 将爬取到的古诗内容保存到文件或数据库中。
  • 对古诗内容进行分析和处理,例如统计词频、提取关键词等。
  • 使用其他爬虫库或工具来提高爬取效率。

希望本教程能帮助您轻松使用 Python 批量爬取古诗文网的完整古诗内容!

Python 批量爬取古诗文网完整古诗内容教程

原文地址: https://www.cveoy.top/t/topic/mwdU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录