【问题标题】:Extracting text from damaged HTML?从损坏的 HTML 中提取文本?
【发布时间】:2015-06-25 06:13:01
【问题描述】:

即使在图书行业,DRM 也是一场瘟疫。上周我发现我的许多 Kindle 注释丢失了,因为出版商试图将注释限制在图书的 10% 以内。

我发现了将 Mobi 图书文件转换为 HTML 的工具。我还使用了位置数据(幸好没有丢失)来提取适当的原始 html 块。我现在的问题是我有很多不完整的标记语言要处理。

例子:

></h1><div height="3em"></div> <p height="0em" width="1em" align="justify"><em>A Pocket Mirror for Heroes</em> is a book of stratagems for reaching excellence in a competitive world ruled by appearances and, often, deceit.</p><div height="0em"></div> <p height="0em" width="1em" align="justify">It is a <em>mirror</em> because it reflects &#x201C;the person you are or the one you ought to be.&#x201D; A <em>pocket</em> mirror because its author took the time to be brief. A mirror for <em>heroes</em> because it provides a vivid image of ethical and moral perfection. For the author, a hero is &#x201C;the consummate person, ripe and perfect: accurate in judgment, mature in taste, attentive in listening, wise in sayings, shrewd in deeds, the cente

这是因为 Kindle 中的位置数据仅对应 150 字节的 HTML 数据块。这意味着有很多不精确性。

我想清理一下。有没有人有什么建议?如果可能,我更喜欢使用 Python。

编辑:也可能有意义的是使用一个可以给字符偏移量的工具,它会计算出如何从中提取清晰的东西。有这样的东西吗?

【问题讨论】:

  • 那块 HTML 是怎么不完整的?
  • 这是一个选择不当的例子。但是还有更广泛的段落,其中许多标签未闭合或包含一半属性。我会更新帖子。

标签: python html screen-scraping kindle


【解决方案1】:

BeautifulSoup 可以解析格式错误的 HTML,而且非常健壮。

>>> html = "<p>Para 1<p>Para 2<blockquote>Quote 1<blockquote>Quote 2"
>>> soup = BeautifulSoup(html)
>>> print(soup.prettify())
<p>
 Para 1
 <p>
  Para 2
  <blockquote>
   Quote 1
   <blockquote>
    Quote 2
   </blockquote>
  </blockquote>
 </p>
</p>

【讨论】:

  • 是的,但是根据 HTML 文档,这不是技术上正确形成的 HTML 吗?这些东西在 HTML 但不是 XHTML 中滑动。无论如何,这是个好主意,我会尝试一下。我可能需要其他东西来做额外的工作。
  • 也许它很健壮,但它似乎并不关心 HTML 规则。 P 在另一个里面?
  • 不是隐含的(例如“任何打开的&lt;p&gt; 将隐式关闭任何以前打开的&lt;p&gt;”)。但它将能够解析损坏的 HTML(甚至是其中的一部分),这很重要。
  • 这出奇的好!我仍然需要解决我的属性被解释为文本的情况。我的想法是,也许我可以检查是否在“”,如果是这样,则回溯直到找到开头的“
  • 我已经尽力了,现在看起来很棒。谢谢 mescalinum 和 BS4 :)
猜你喜欢
  • 1970-01-01
  • 2013-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多