python - BeautifulSoup - 处理自动关闭标签的正确方法

标签 python beautifulsoup

我有一个带有一些自闭合标签的 html 文件,但 BeautifulSoup 不喜欢它们。

from bs4 import BeautifulSoup
html = '<head><meta content="text/html" http-equiv="Content-Type"><meta charset="utf-8"></head>'
doc = BeautifulSoup(html, 'html.parser')
print doc.prettify()

打印

<head>
 <meta content="text/html" http-equiv="Content-Type">
   <meta charset="utf-8"/>
 </meta>
</head>

我是否必须手动检查每个标签是否自动关闭并进行适当修改,或者是否有更好的处理方法?

最佳答案

您可能已经知道,您可以指定 BeautifulSoup 将在内部使用的不同解析器。并且,如 BeautifulSoup docs 中所述:

There are also differences between HTML parsers. If you give Beautiful Soup a perfectly-formed HTML document, these differences won’t matter. One parser will be faster than another, but they’ll all give you a data structure that looks exactly like the original HTML document.

But if the document is not perfectly-formed, different parsers will give different results.

在这种特殊情况下,lxmlhtml5lib 都会生成两个单独的 meta 标记:

In [4]: doc = BeautifulSoup(html, 'lxml')
In [5]: print(doc.prettify())
<html>
 <head>
  <meta content="text/html" http-equiv="Content-Type"/>
  <meta charset="utf-8"/>
 </head>
</html>

In [6]: doc = BeautifulSoup(html, 'html5lib')
In [7]: print(doc.prettify())
<html>
 <head>
  <meta content="text/html" http-equiv="Content-Type"/>
  <meta charset="utf-8"/>
 </head>
 <body>
 </body>
</html>

关于python - BeautifulSoup - 处理自动关闭标签的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33458356/

相关文章:

python - 如何确保Python中只有一个线程实例在运行?

python - 通过给定的索引对列表删除子字符串

python - 使用 Python 2 的 Anaconda 发行版安装 gmpy (Windows)

python - BeautifulSoup 内容的正确编码

python - 如何使用 BeautifulSoup 从嵌套在 <li> 中的 <span> 中提取文本,而 <li> 嵌套在 <ul> 中?

Python dictreader KeyError 问题

python - 在 Django Rest FrameWork 中检索 HTTP header

python - pip install bs4 给出 _socketobject 错误

python - 从网上提取表格

python - 如何选择美丽汤列表中每个元素的第一个子元素