Python 组合测试对象类型

Python 组合测试对象类型,python,beautifulsoup,Python,Beautifulsoup,下午好 我正在使用BeautifulSoup加载和解析html文件的内容 我的输入是这样的 <tbody id="data"> <tr> <td> some text </td> </tr> from bs4 import BeautifulSoup with open('table.htm') as f: src_html=BeautifulSoup(f,"html.parser") table=src_htm

下午好

我正在使用BeautifulSoup加载和解析html文件的内容

我的输入是这样的

<tbody id="data">

    <tr>
<td>
  some text </td>
</tr>
from bs4 import BeautifulSoup
with open('table.htm') as f:
    src_html=BeautifulSoup(f,"html.parser")
table=src_html.find(id="data")
type(table.contents[0])  # bs4.element.NavigableString
type(table.contents[1])  # bs4.element.Tag
因为我的表有几个单元格,所以我想得到类型为bs4.element.Tag的单元格,我该怎么做

for c in table.children:
    if type(c) is bs4.element.Tag then do something
谢谢你的帮助


西蒙

我找到了回答我问题的方法

from bs4.element import NavigableString, Tag
cells = [ t for t in table.contents if isinstance(t, Tag) ]

您最终要从表中提取什么?我只想提取cell()内容,但看起来每个单元格都用一个“\r”分隔,表示为一个NavigableString,我想我找到了我的代码的错误之处谢谢,这对我来说真的不明显。我仍然不明白为什么不能直接执行isinstance(mybs4elementTag,type('bs4.element.Tag'))