Loading page...Загружаем страницу...正在加载页面...
AtlasRepo

Parsing and Rebuilding EPUB Files in Python: Lessons Learned

Description and use

The article explains how to translate EPUB files while preserving layout by reading with ebooklib, editing HTML with lxml, and rebuilding the EPUB via direct ZIP manipulation.

Problem

Translating EPUBs while preserving layout, images, and styles requires precise in‑place HTML modification, which standard EPUB libraries struggle to provide.

Outcome

The pipeline now reliably translates EPUBs, maintaining original layout, images, and navigation, by combining ebooklib for reading, lxml for precise HTML editing, and direct ZIP handling for final packaging.

Workflow

  • Read EPUB with ebooklib
  • Iterate over ITEM_DOCUMENT items
  • Parse each XHTML with lxml’s HTMLParser
  • Traverse tree, skip script/style, replace text nodes using a translation map
  • Return modified XHTML bytes
  • Extract original EPUB to temp directory
  • Overwrite modified XHTML files
  • Re‑zip directory ensuring 'mimetype' is first and uncompressed
  • Write new EPUB

Evidence

ebooklib’s high‑level API is designed for creating new EPUBs from scratch, not for surgical modification.

Source

We realized we needed to treat the EPUB as a ZIP archive of XHTML files and operate directly on those files.

Source

  • Record date: 2026-10-21T03:41:27.382Z