python 爬取文本内容并写入json文件

背景: 项目需要从html 提取说明书目录

实现: 由于html是包含所有内容,所以将其中目录部分手动重新生成一个html 文件dir26.html

python

python 复制代码
import requests
from bs4 import BeautifulSoup
import json

filename = "dir26.html"  # 替换为实际的文件路径
with open(filename, "r") as file:
    html = file.read()
    soup = BeautifulSoup(html, "html.parser")

results = soup.find_all('div') # 根据需要修改选择器
# print("soup:",soup)
# print("results:",results)

# 提取数据并转换为JSON格式
data = []
for result in results:
    #print(result.text)
    resulttext = result.text
    directory = resulttext.split(" ")[0] // 取第一个空格之前的内容
    print(directory)
    page = resulttext.split(" ")[2]//取第三个空格之前的内容
    print(page)
    data.append({'directory': directory, 'page': page})

# 写入JSON文件
with open("manualdir.json", "w") as file:
    json.dump(data, file, ensure_ascii=False)

android中读取Json 中的内容代码:

java 复制代码
// 存储Json中的信息
private LinkedHashMap<String, String> mDirMap = new LinkedHashMap<String, String>();
private void initDirectory() {
        byte[] buffer;
        try {
            //将json文件读取到buffer数组中
            InputStream is = 
                 getContext().getResources().getAssets().open("manualdir.json");
            buffer = new byte[is.available()];
            is.read(buffer);
        } catch (IOException e) {
            Log.w(TAG, "manual dir json IOException e:" + e);
            return;
        }

        //  将字符数组转换为UTF-8编码的字符串
        String json;
        try {
            json = new String(buffer, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            Log.w(TAG, "manual dir json UnsupportedEncodingException e" + e);
            return;
        }

        //将字符串json转换为json对象,以便于取出数据
        try {

            JSONArray jsa = new JSONArray(json);
            for (int i = 0; i < jsa.length();i++){
                JSONObject jso = jsa.getJSONObject(i);

                Log.w(TAG, " jsa.length():" +  jsa.length());
                String title = jso.optString("directory");//标题
                Log.w(TAG, "title:"+title);
                int page = jso.optInt("page");//目录页数
                mDirMap.put(title, "#pf"+Integer.toHexString(page));
            }
        } catch (JSONException e) {
            Log.w(TAG, "manual dir json exception e:"+e);
        }
    }
相关推荐
加成BUFF4 分钟前
基于DeepSeek+Python开发软件并打包为exe(VSCode+Anaconda Prompt实操)
vscode·python·prompt·conda·anaconda
星火开发设计17 分钟前
异常规范与自定义异常类的设计
java·开发语言·前端·c++
xyq202418 分钟前
SQL Mid() 函数详解
开发语言
52Hz11828 分钟前
力扣46.全排列、78.子集、17.电话号码的字母组合
python·leetcode
子午34 分钟前
【宠物识别系统】Python+深度学习+人工智能+算法模型+图像识别+TensorFlow+2026计算机毕设项目
人工智能·python·深度学习
好家伙VCC35 分钟前
# 发散创新:用Python+Pandas构建高效BI数据清洗流水线在现代数据分析领域,**BI(商业智能)工具的核心竞
java·python·数据分析·pandas
文艺倾年44 分钟前
【源码精讲+简历包装】LeetcodeRunner—手搓调试器轮子(20W字-下)
java·开发语言·人工智能·语言模型·自然语言处理·大模型·免训练
松叶似针1 小时前
Flutter三方库适配OpenHarmony【secure_application】— Android 端 FLAG_SECURE 实现分析
android·flutter
七夜zippoe1 小时前
TensorFlow 2.x深度实战:从Keras API到自定义训练循环
人工智能·python·tensorflow·keras
励ℳ1 小时前
Python环境操作完全指南
开发语言·python