将所有 HTML Parser 的函数签名从接收 HTML 字符串改为接收文件路径, 与其他 Reader(PDF、DOCX 等)保持一致。 主要变更: - 修改 PARSERS 列表,移除 lambda 表达式,直接传递函数引用 - 在 HtmlReader.parse() 中统一管理临时文件(UTF-8 编码) - 每个 Parser 使用独立的临时文件副本,用完即清理 - 移除 download_and_parse() 方法,逻辑合并到 parse() 中 - 更新相关测试,改为直接传递文件路径 受影响的 Parser: - trafilatura.parse(html_content) -> parse(file_path) - domscribe.parse(html_content) -> parse(file_path) - markitdown.parse(html_content, temp_file_path) -> parse(file_path) - html2text.parse(html_content) -> parse(file_path)
39 lines
1.2 KiB
Python
39 lines
1.2 KiB
Python
"""使用 trafilatura 解析 HTML"""
|
|
|
|
from typing import Optional, Tuple
|
|
|
|
|
|
def parse(file_path: str) -> Tuple[Optional[str], Optional[str]]:
|
|
"""使用 trafilatura 解析 HTML 文件"""
|
|
try:
|
|
import trafilatura
|
|
except ImportError:
|
|
return None, "trafilatura 库未安装"
|
|
|
|
try:
|
|
with open(file_path, 'r', encoding='utf-8') as f:
|
|
html_content = f.read()
|
|
except FileNotFoundError:
|
|
return None, f"文件不存在: {file_path}"
|
|
except Exception as e:
|
|
return None, f"读取文件失败: {str(e)}"
|
|
|
|
try:
|
|
markdown_content = trafilatura.extract(
|
|
html_content,
|
|
output_format="markdown",
|
|
include_formatting=True,
|
|
include_links=True,
|
|
include_images=False,
|
|
include_tables=True,
|
|
favor_recall=True,
|
|
include_comments=True,
|
|
)
|
|
if markdown_content is None:
|
|
return None, "trafilatura 返回 None"
|
|
if not markdown_content.strip():
|
|
return None, "解析内容为空"
|
|
return markdown_content, None
|
|
except Exception as e:
|
|
return None, f"trafilatura 解析失败: {str(e)}"
|