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);
        }
    }
相关推荐
才疏学浅7431 分钟前
批量下载鹏程实验室数据的方法
java·开发语言·word
m0_596749092 分钟前
C#怎么使用with表达式 C#record类型中with表达式怎么用如何创建对象的修改副本【语法】
jvm·数据库·python
神明9314 分钟前
uni-app动画效果实现 uni-app如何使用animation API
jvm·数据库·python
m0_690825825 分钟前
uni-app怎么做类似于微博的新消息气泡 uni-app角标动画效果实现【代码】
jvm·数据库·python
m0_631529825 分钟前
uni-app iOS后台运行 uni-app App如何实现后台定位或音乐播放
jvm·数据库·python
2301_779622416 分钟前
如何睡眠等待_DBMS_LOCK.SLEEP与DBMS_SESSION暂停当前会话
jvm·数据库·python
皮卡祺q8 分钟前
【JVM】:类加载机制,jvm内存布局,垃圾回收,String 不可变性源码分析
java·开发语言·jvm·多线程·string
2303_821287389 分钟前
CSS中如何实现绝对定位元素的等比缩放_利用宽高百分比
jvm·数据库·python
码农学院9 分钟前
JSON 里是一个空字符串 ““,Newtonsoft.Json 无法直接把字符串转成列表
json
JAVA面经实录91710 分钟前
Java核心底层原理全集(终版无遗漏·生产级PDF)
java·开发语言·学习