Python 选择尚未选择为相同图元的子体的标记

Python 选择尚未选择为相同图元的子体的标记,python,beautifulsoup,Python,Beautifulsoup,使用BeautifulSoup,我想选择所有类为“main”的表,这些表还没有被选为相同元素的后代。 在lxml中,以下代码起作用: root.xpath('//table[@class="main" and not(ancestor::table[@class="main"])]') 但是我怎么能在美丽的城市里做到这一点呢 谢谢你的帮助!:) 这可能不是最有效的解决方案,但应该可以: nested_tables = soup.select('table.main table.main') t

使用BeautifulSoup,我想选择所有类为“main”的表,这些表还没有被选为相同元素的后代。 在lxml中,以下代码起作用:

root.xpath('//table[@class="main" and not(ancestor::table[@class="main"])]')
但是我怎么能在美丽的城市里做到这一点呢


谢谢你的帮助!:)

这可能不是最有效的解决方案,但应该可以:

nested_tables = soup.select('table.main table.main')
tables = [t for t in soup.select('table.main') if t not in nested_tables]
您也可以这样做:

tables = [t for t in soup.select('table.main') 
          if not t.find_parents('table', class_='main')]