Python 如何在BeautifulSoup中的findPrevious函数中区分打开标记和关闭标记?

Python 如何在BeautifulSoup中的findPrevious函数中区分打开标记和关闭标记?,python,tags,beautifulsoup,Python,Tags,Beautifulsoup,我想查找搜索的项是否包含在表中。我使用以下代码: tableprevious = foundtext.findPrevious('table') 但是,此代码将引用 <table> or </table> 或 并且无法区分foundtext是否已在表中。有什么想法吗?试试findParent()方法。如果一个项包含在一个表中,它将有一个表标记作为祖先。例如: from BeautifulSoup import BeautifulSoup html = '<t

我想查找搜索的项是否包含在表中。我使用以下代码:

tableprevious = foundtext.findPrevious('table')
但是,此代码将引用

<table> or </table>
并且无法区分foundtext是否已在表中。有什么想法吗?

试试
findParent()
方法。如果一个项包含在一个表中,它将有一个表标记作为祖先。例如:

from BeautifulSoup import BeautifulSoup

html = '<table><tr><td><b>In table</b></td></tr></table><b>Not in table</b>'
soup = BeautifulSoup(html)
items = soup('b')
for item in items:
    if item.findParent('table'):
        print item
从美化组导入美化组
html='In table not In table'
soup=BeautifulSoup(html)
项目=汤('b')
对于项目中的项目:
如果item.findParent('table'):
打印项目
这将产生:

<b>In table</b>
表中的
foundPrevious()
返回
?完美。非常感谢你@Josh Rosen。