BeautifulSoup按类搜索
可能重复的问题:
Beautiful Soup无法找到一个CSS类,如果这个对象还有其他类
我正在使用BeautifulSoup来查找HTML中的tables
(表格)。我现在遇到的问题是关于class
属性中空格的使用。如果我的HTML是<html><table class="wikitable sortable">blah</table></html>
,我似乎无法用下面的方式提取它(我本来可以用wikipedia
和wikipedia sortable
来找到class
):
BeautifulSoup(html).findAll(attrs={'class':re.compile("wikitable( sortable)?")})
不过,如果我的HTML只是<html><table class="wikitable">blah</table></html>
,这样就能找到表格。同样,我也尝试在我的正则表达式中使用"wikitable sortable"
,但这也不匹配。有什么想法吗?
2 个回答
8
lxml比BeautifulSoup更好的一个原因是,它支持像CSS那样的类选择功能(如果你想用的话,它甚至支持完整的CSS选择器)。
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>
24
如果在一个元素的类属性中,wikitable
出现在其他CSS类之后,比如说class="something wikitable other"
,那么模式匹配就会失败。所以如果你想找到所有类属性中包含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,就像其他人提到的那样。