【发布时间】:2015-04-19 17:58:03
【问题描述】:
我正在使用 Python 中的 BeautifulSoup 将大量 HTML 文件大量转换为 XML。
示例 HTML 文件如下所示:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- this is an HTML comment -->
<!-- this is another HTML comment -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
...
<!-- here is a comment inside the head tag -->
</head>
<body>
...
<!-- Comment inside body tag -->
<!-- Another comment inside body tag -->
<!-- There could be many comments in each file and scattered, not just 1 in the head and three in the body. This is just a sample. -->
</body>
</html>
<!-- This comment is the last line of the file -->
我想出了如何找到文档类型并将其替换为标签<doctype>...</doctype>,但评论让我很沮丧。我想用<comment>...</comment> 替换HTML cmets。在这个 HTML 示例中,我能够替换前两个 HTML cmets,但 html 标记内的任何内容和结束 html 标记之后的最后一个注释我都没有。
这是我的代码:
file = open ("sample.html", "r")
soup = BeautifulSoup(file, "xml")
for child in soup.children:
# This takes care of the first two HTML comments
if isinstance(child, bs4.Comment):
child.replace_with("<comment>" + child.strip() + "</comment>")
# This should find all nested HTML comments and replace.
# It looks like it works but the changes are not finalized
if isinstance(child, bs4.Tag):
re.sub("(<!--)|(<!--)", "<comment>", child.text, flags=re.MULTILINE)
re.sub("(-->)|(--&gr;)", "</comment>", child.text, flags=re.MULTILINE)
# The HTML comments should have been replaced but nothing changed.
print (soup.prettify(formatter=None))
这是我第一次使用 BeautifulSoup。如何使用 BeautifulSoup 查找并替换所有带有 <comment> 标签的 HTML cmets?
我可以通过pickle 将其转换为字节流,对其进行序列化,应用正则表达式,然后将其反序列化回BeautifulSoup 对象吗?这会起作用还是只会导致更多问题?
我尝试在子标记对象上使用pickle,但反序列化失败并出现TypeError: __new__() missing 1 required positional argument: 'name'。
然后我尝试通过child.text 仅腌制标签的文本,但由于AttributeError: can't set attribute,反序列化失败。基本上,child.text 是只读的,这就解释了为什么正则表达式不起作用。所以,我不知道如何修改文本。
【问题讨论】:
-
应用所有更改后不会导致格式错误的
xml文件吗? -
我不知道,但
Chilkat有一个(不是免费的)HTML-to-XML 转换 python 库,可以将所有 HTML cmets 转换为<comment>,并且 XML 文件看起来不错。
标签: python html regex xml beautifulsoup