BeautifulSoup和按类搜索

cry*_*tar 13 python beautifulsoup

可能重复:
如果对象也有其他类,Beautiful Soup也找不到CSS类

我正在使用BeautifulSoup tables在HTML中查找.我目前遇到的问题是在class属性中使用空格.如果我的HTML读取<html><table class="wikitable sortable">blah</table></html>,我似乎无法使用以下内容提取它(我可以在tables两者中找到它wikipedia并且wikipedia sortable用于class):

BeautifulSoup(html).findAll(attrs={'class':re.compile("wikitable( sortable)?")})
Run Code Online (Sandbox Code Playgroud)

如果我的HTML就是这样,我们会找到该表<html><table class="wikitable">blah</table></html>.同样,我尝试"wikitable sortable"在我的正则表达式中使用,但也不匹配.有任何想法吗?

sam*_*ias 24

如果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
Run Code Online (Sandbox Code Playgroud)

结果:

<table class="sortable wikitable other">blah</table>
<table class="wikitable sortable">blah</table>
<table class="wikitable"><blah></blah></table>
Run Code Online (Sandbox Code Playgroud)

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

  • 就像更新一样,最新版本的BeautifulSoup(bs4)处理得更加优雅:http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class (2认同)

Aco*_*orn 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)
Run Code Online (Sandbox Code Playgroud)

得到:

<div class="bread butter"></div>
<div class="bread"></div>
Run Code Online (Sandbox Code Playgroud)