基于 Python 的文本内容提取及 JSON 格式存储

介绍如何使用 Python 爬取文本内容,提取目录及对应页码信息,并将结果保存为结构化的 JSON 文件。

1. 环境配置

确保已安装以下 Python 库:

  • requests:用于发送 HTTP 请求获取网页内容。
  • beautifulsoup4: 用于解析 HTML 文档,提取所需信息。
  • json: 用于处理 JSON 数据格式。

可以使用 pip 命令安装:

bash

pip install requests beautifulsoup4 json

### 2. 代码实现

```python

import requests

from bs4 import BeautifulSoup

import json

def extract_toc(url):

response = requests.get(url)

response.encoding = 'utf-8'

soup = BeautifulSoup(response.text, 'html.parser')

 toc = []
 for element in soup.select('your_selector_here'): 
     title = element.text.strip()
     page_num = element['href'].split('#')[-1]  
     toc.append({'title': title, 'page': page_num})

 return toc

if name == 'main':

url = 'https://www.example.com'

toc_data = extract_toc(url)

 with open('toc.json', 'w', encoding='utf-8') as f:
     json.dump(toc_data, f, ensure_ascii=False, indent=4)

```

代码说明:

  1. 替换 'your_selector_here' 为实际网页中目录条目的 CSS 选择器。
  2. 根据网页结构调整提取标题和页码的逻辑。
  3. 'https://www.example.com' 替换为目标网页链接。

### 3. 运行结果

运行代码后,将在当前目录下生成 toc.json 文件,内容为提取的目录信息,格式如下:

json

[

{

"title": "第一章 简介",

"page": "page_1"

},

{

"title": "第二章 内容概述",

"page": "page_10"

}

]

该方法可根据实际需求调整代码,实现灵活的文本内容提取和 JSON 数据存储。

html 文件大小:27.91KB