美化群体,分类搜索

2024-05-13 17:58:43 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Beautiful Soup cannot find a CSS class if the object has other classes, too

我正在使用BeautifulSoup在HTML中查找tables。我目前遇到的问题是在class属性中使用空格。如果我的HTML读取的是<html><table class="wikitable sortable">blah</table></html>,那么我似乎无法用以下方法提取它(在这里,我可以用wikipediawikipedia sortable同时找到classtables):

BeautifulSoup(html).findAll(attrs={'class':re.compile("wikitable( sortable)?")})

如果我的HTML只是<html><table class="wikitable">blah</table></html>的话,这将找到表。同样,我也尝试过在正则表达式中使用"wikitable sortable",但这也不匹配。有什么想法吗?


Tags: tableshtmltablewikipediaclassblahsoupbeautiful
2条回答

如果wikitable出现在另一个CSS类之后(如class="something wikitable other"),那么模式匹配也将失败,因此,如果希望其class属性包含类wikitable的所有表都需要接受更多可能性的模式:

html = '''<html><table class="sortable wikitable other">blah</table>
<table class="wikitable sortable">blah</table>
<table class="wikitable"><blah></table></html>'''

tree = BeautifulSoup(html)
for node in tree.findAll(attrs={'class': re.compile(r".*\bwikitable\b.*")}):
    print node

结果:

<table class="sortable wikitable other">blah</table>
<table class="wikitable sortable">blah</table>
<table class="wikitable"><blah></blah></table>

为了便于记录,我不使用BeautifulSoup,而是喜欢使用lxml,正如其他人提到的那样。

使lxml比BeautifulSoup更好的一点是支持适当的CSS类选择(如果您想使用它们,甚至支持full css selectors

import lxml.html

html = """<html>
<body>
<div class="bread butter"></div>
<div class="bread"></div>
</body>
</html>"""

tree = lxml.html.fromstring(html)

elements = tree.find_class("bread")

for element in elements:
    print lxml.html.tostring(element)

给出:

<div class="bread butter"></div>
<div class="bread"></div>

相关问题 更多 >