开发者

How can I distinguish between an open tag and a closed tag in the findPrevious function in BeautifulSoup?

I want to find if a searched item is contained within a table. I use the following code:

tableprevious = foundtext.findPrevious('table')

However, this code will ref开发者_开发问答er to either

<table> or </table>

and doesn't make it possible to distinguish if the foundtext is already in a table. Any ideas?


Try the findParent() method. If an item is contained in a table, it will have a table tag as an ancestor. Example:

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

This outputs:

<b>In table</b>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜