如何在Python中解析格式错误的HTML

发布于 2024-07-21 04:41:49 字数 247 浏览 5 评论 0原文

我需要浏览已解析的 HTML 文档的 DOM 树。

解析字符串之前使用 uTidyLib

我在使用 lxml a = tidy.parseString(html_code, options) dom = etree.fromstring(str(a))

有时我会收到错误,似乎 tidylib 无法修复格式错误的 html。

如何解析每个 HTML 文件而不出现错误(仅解析文件中无法修复的某些部分)?

I need to browse the DOM tree of a parsed HTML document.

I'm using uTidyLib before parsing the string with lxml

a = tidy.parseString(html_code, options)
dom = etree.fromstring(str(a))

sometimes I get an error, it seems that tidylib is not able to repair malformed html.

how can I parse every HTML file without getting an error (parsing only some parts of files that can not be repaired)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

要走干脆点 2024-07-28 04:41:49

Beautiful Soup 可以很好地处理无效/损坏的 HTML

>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("<htm@)($*><body><table <tr><td>hi</tr></td></body><html")
>>> print soup.prettify()
<htm>
 <body>
  <table>
   <tr>
    <td>
     hi
    </td>
   </tr>
  </table>
 </body>
</htm>

Beautiful Soup does a good job with invalid/broken HTML

>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("<htm@)($*><body><table <tr><td>hi</tr></td></body><html")
>>> print soup.prettify()
<htm>
 <body>
  <table>
   <tr>
    <td>
     hi
    </td>
   </tr>
  </table>
 </body>
</htm>
本王不退位尔等都是臣 2024-07-28 04:41:49

既然您已经在使用 lxml,那么您是否尝试过 lxml 的 ElementSoup 模块?

如果 ElementSoup 无法修复 HTML,那么您可能需要首先应用自己的过滤器,这些过滤器基于您自己对数据损坏方式的观察。

Since you are already using lxml, have you tried lxml's ElementSoup module?

If ElementSoup can't repair the HTML then you'll probably need to apply your own filters first that are based on your own observations of how the data is broken.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文