gpt4 book ai didi

python - 为什么 BeautifulSoup .children 包含无名元素以及预期的标签

转载 作者:太空宇宙 更新时间:2023-11-04 03:56:12 25 4
gpt4 key购买 nike

代码

#!/usr/bin/env python3
from bs4 import BeautifulSoup

test="""<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<title>Test</title>
</head>
<body>
<table>
<tbody>
<tr>
<td>
<div>
<b>
Icon
</b>
</div>
</td>
</tr>
</tbody>
</table>
</body>
</html>"""

soup = BeautifulSoup(test2)
rows = soup.findAll('tr')
for r in rows:
print(r.name)
for c in r.children:
print('>', c.name)

输出

tr
> None
> td
> None

为什么该行的 child 列表中有无名元素?

这发生在 Windows 8 上运行 Python 3.3.1 64 位时,使用 html.parser(这是 Python 的内置解析器)。

最佳答案

.children 的元素可以是NavigableStrings以及Tags .在您的示例中,它们是 td 元素前后的空格。

希望您的代码的这种变体可以清楚地表明:

>>> rows = soup.findAll('tr')
>>> for r in rows:
... print("row:", r.name)
... for c in r.children:
... print("---")
... print(type(c))
... print(repr(c))
...
row: tr
---
<class 'bs4.element.NavigableString'>
'\n'
---
<class 'bs4.element.Tag'>
<td>
<div>
<b>
Icon
</b>
</div>
</td>
---
<class 'bs4.element.NavigableString'>
'\n'

关于python - 为什么 BeautifulSoup .children 包含无名元素以及预期的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18284524/

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