使用BeautifulSoup,我想选择所有类“main”的表,这些表尚未被选为相同元素的后代。 在lxml中,以下代码有效:
root.xpath('//table[@class="main" and not(ancestor::table[@class="main"])]')
但是我怎么能在BeautifulSoup中做到这一点?
感谢您的帮助! :)
答案 0 :(得分:2)
这可能不是最有效的解决方案,但它应该有效:
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')]