Skip to main content
 首页 » 编程设计

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

2024年11月01日9xxx_UU

代码

#!/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'