gpt4 book ai didi

python - 在 BeautifulSoup 中解析 MS 特定的 html 标签

转载 作者:太空宇宙 更新时间:2023-11-04 00:22:01 24 4
gpt4 key购买 nike

在尝试解析使用 MS Outlook 发送的电子邮件时,我希望能够去除它添加的烦人的 Microsoft XML 标签。一个这样的例子是 o:p 标签。当尝试使用 Python 的 BeautifulSoup 将电子邮件解析为 HTML 时,它似乎无法找到这些特殊标签。

例如:

from bs4 import BeautifulSoup

textToParse = """
<html>
<head>
<title>Something to parse</title>
</head>
<body>
<p><o:p>This should go</o:p>Paragraph</p>
</body>
</html>
"""

soup = BeautifulSoup(textToParse, "html5lib")

body = soup.find('body')

for otag in body.find_all('o'):
print(otag)

for otag in body.find_all('o:p'):
print(otag)

这将不会向控制台输出任何文本,但是如果我将 find_all 调用切换为搜索 p 那么它将输出 p节点符合预期。

为什么这些自定义标签似乎不起作用?

最佳答案

这是一个命名空间问题。显然,当使用 "html5lib" 进行解析时,BeautifulSoup 不认为自定义命名空间有效。

您可以使用正则表达式来解决这个问题,奇怪的是,它确实可以正常工作!

print (soup.find_all(re.compile('o:p')))
>>> [<o:p>This should go</o:p>]

但“正确”的解决方案是将解析器更改为 "lxml-xml" 并引入 o: 作为有效的命名空间。

from bs4 import BeautifulSoup

textToParse = """
<html xmlns:o='dummy_url'>
<head>
<title>Something to parse</title>
</head>
<body>
<p><o:p>This should go</o:p>Paragraph</p>
</body>
</html>
"""

soup = BeautifulSoup(textToParse, "lxml-xml")

body = soup.find('body')

print ('this should find nothing')
for otag in body.find_all('o'):
print(otag)

print ('this should find o:p')
for otag in body.find_all('o:p'):
print(otag)

>>>
this should find nothing
this should find o:p
<o:p>This should go</o:p>

关于python - 在 BeautifulSoup 中解析 MS 特定的 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48795945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com