BeautifulSoup 从 MDict 的 html中提取 image/jpeg;base64
extract_mdx_img.py
# -*- coding: UTF-8 -*-
import os
import sys
import bs4
import base64
from readmdict import MDX # pip install readmdict
# data:image/jpeg;base64,/9j/
def base64ToImage(name, base64res):
if base64res.startswith("data:image/jpeg"):
ext = '.jpg'
else:
ext = '.png'
res = base64res.split(",")[1]
img_b64decode = base64.b64decode(res)
# 输出文件夹是否存在
if not os.path.exists("img"):
os.makedirs("img")
print("mkdir img success")
# 输出图片
fname = "img/" +name +ext
print(fname)
with open(fname, 'wb') as img:
img.write(img_b64decode)
with open("img_url.htm","a+", encoding="utf8") as fp:
url = f'<h3>{name}</h3> <img src="' +fname + '" /><p>\n'
fp.write(url)
# main()
if len(sys.argv) ==2:
queryWord = sys.argv[1]
else:
print("usage: extract_mdx_img.py queryWord ")
sys.exit(1)
path1 ="你的MDict 词典目录"
os.chdir(path1)
# 加载mdx文件
filename = "你的词典文件名"
mdx = MDX(filename)
headwords = [*mdx] # 单词名列表
items = [*mdx.items()] # 释义html源码列表
n = len(headwords)
m = len(items)
if n == m:
print(f'加载成功:共{n}条')
else:
print(f'ERROR:加载失败 {n}!={m}')
sys.exit(2)
# 查词,返回单词和html文件
wordIndex = headwords.index(queryWord.encode())
word,html = items[wordIndex]
word,html = word.decode(), html.decode()
print(word)
# 从html中提取 image/jpeg;base64
soup = bs4.BeautifulSoup(html, features='html.parser')
i=0
for img in soup.find_all("img"):
i +=1
base64ToImage(f"{queryWord}_"+str(i), img.get("src"))
print("生成图片",i,"张")
运行 extract_mdict_img.py point
或者 python extract_mdict_img.py compass
显示图片,双击文件 img_url.htm
该Python脚本利用BeautifulSoup库解析MDict词典文件中的HTML,提取以base64编码的JPEG或PNG图像,并将它们保存为本地文件。脚本接受命令行参数作为查询词,找到对应的词典条目,然后将提取的图片保存在img目录下,并在img_url.htm文件中创建一个链接列表以便查看。

33

被折叠的 条评论
为什么被折叠?



