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);
        }
    }
相关推荐
2601_949146537 分钟前
Python语音通知API示例代码汇总:基于Requests库的语音接口调用实战
开发语言·python
去码头整点薯条9812 分钟前
python第五次作业
linux·前端·python
3GPP仿真实验室13 分钟前
【Matlab源码】6G候选波形:OFDM-IM 索引调制仿真平台
开发语言·matlab
darling33115 分钟前
mysql 自动备份以及远程传输脚本,异地备份
android·数据库·mysql·adb
有代理ip25 分钟前
Python 与 Golang 爬虫的隐藏优势
爬虫·python·golang
数研小生26 分钟前
1688商品列表API:高效触达批发电商海量商品数据的技术方案
大数据·python·算法·信息可视化·json
Coder_Boy_29 分钟前
基于SpringAI的在线考试系统-企业级教育考试系统核心架构(完善版)
开发语言·人工智能·spring boot·python·架构·领域驱动
你刷碗32 分钟前
基于S32K144 CESc生成随机数
android·java·数据库
2301_7657031434 分钟前
C++中的代理模式变体
开发语言·c++·算法
咚为35 分钟前
Rust tokio:Task ≠ Thread:Tokio 调度模型中的“假并发”与真实代价
开发语言·后端·rust