if not page.image: 报错 if not page.image: ^^^^^^^^^^ File "D:\install\Python312\Lib\site-packages\pydantic\main.py", line 988, in __getattr__ return super().__getattribute__(item) # Raises AttributeError if appropriate ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\install\Python312\Lib\site-packages\docling\datamodel\base_models.py", line 271, in image return self.get_image(scale=self._default_image_scale) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\install\Python312\Lib\site-packages\docling\datamodel\base_models.py", line 254, in get_image self._image_cache[scale] = self._backend.get_page_image(scale=scale) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\install\Python312\Lib\site-packages\docling\backend\docling_parse_v4_backend.py", line 96, in get_page_image page_size = self.get_size() ^^^^^^^^^^^^^^^ File "D:\install\Python312\Lib\site-packages\docling\backend\docling_parse_v4_backend.py", line 131, in get_size return Size(width=self._ppage.get_width(), height=self._ppage.get_height()) ^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'get_width'
时间: 2025-06-01 18:08:53 浏览: 5
从错误信息来看,问题出在 `page.image` 的调用过程中。具体来说,`self._ppage` 是 `NoneType`,导致无法调用其方法 `get_width()`。这表明某些页面的底层数据可能没有正确初始化。
以下是针对该问题的解决方案和改进代码。
---
### 回答问题
#### 修改代码以适配潜在的空值
为了防止因 `self._ppage` 为 `None` 导致的错误,我们需要在访问 `page.image` 之前增加检查逻辑。如果 `page.image` 或其依赖的数据为空,则跳过当前页面的图片处理。
以下是改进后的代码:
```python
import pathlib
import time
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import PdfPipelineOptions, EasyOcrOptions
from docling.document_converter import DocumentConverter, PdfFormatOption
# 指定模型路径
artifacts_path = "D:/model/docling-models"
# 指定OCR模型
easyocr_options = EasyOcrOptions()
# 支持中文和英文
easyocr_options.lang = ['ch_sim', 'en']
pipeline_options = PdfPipelineOptions(artifacts_path=artifacts_path)
# 设置支持OCR
pipeline_options.do_ocr = True
# 设置支持表结构
pipeline_options.do_table_structure = True
# 指定OCR模型,可以不设置
pipeline_options.ocr_options = easyocr_options
start_time = time.time()
# 初始化转换器
converter = DocumentConverter(
format_options={
InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)
}
)
# 源文件路径
source = "../data/Docling文档.pdf"
result = converter.convert(source)
# 检查是否有页面数据
if not result.pages:
print("警告:PDF 文件中未提取到任何页面数据!")
else:
print(f"成功提取 {len(result.pages)} 页数据。")
# 提取并保存图片
pictures_directory = pathlib.Path("../data/pictures/")
pictures_directory.mkdir(parents=True, exist_ok=True) # 确保目录存在
for page_index, page in enumerate(result.pages):
print(f"处理第 {page_index} 页...")
try:
# 检查是否有图片数据
if hasattr(page, 'image'):
image_bytes = page.image
if image_bytes:
image_path = pictures_directory / f"{page_index}.png"
image_path.write_bytes(image_bytes)
print(f"已保存图片至 {image_path}")
else:
print(f"警告:第 {page_index} 页中的图片数据为空!")
else:
print(f"警告:第 {page_index} 页未检测到图片属性!")
except AttributeError as e:
print(f"错误:处理第 {page_index} 页时发生异常 - {e}")
# 导出为HTML
md_text = result.document.export_to_html()
if not md_text:
print("警告:未能成功导出HTML内容!")
else:
html_path = pathlib.Path("../data/Docling文档.html")
html_path.write_bytes(md_text.encode())
print(f"已保存HTML文件至 {html_path}")
print("--- %s seconds ---" % (time.time() - start_time))
```
---
### 解释代码改进点
1. **增加异常捕获**
使用 `try-except` 块捕获可能的 `AttributeError` 异常,确保程序不会因单个页面的问题而崩溃。
2. **检查图片数据是否为空**
在访问 `page.image` 后,进一步检查其是否为空。如果为空,输出警告信息并继续处理下一页。
3. **增强日志输出**
在每个页面处理完成后,输出详细的日志信息,帮助用户了解哪些页面存在问题。
4. **保持目录创建逻辑**
确保图片保存目录存在,避免因目录缺失导致的错误。
---
###
阅读全文
相关推荐


















