【问题标题】:BeautifulSoup and Searching By Class [duplicate]BeautifulSoup 和按类搜索 [重复]
【发布时间】:2011-08-18 22:32:49
【问题描述】:

可能重复:
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 中找到 tables class):

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

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

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    如果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,正如其他人提到的那样。

    【讨论】:

    【解决方案2】:

    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>
    

    【讨论】:

    • +1 尽管这对@allie 编写 BeautifulSoup 代码没有帮助,但 lxml 却要好得多。
    • 虽然我很欣赏它的优雅,但 BeautifulSoup 已经存在,而且目前,这就是我需要使用的东西。 :)
    • 之所以这么多人喜欢 BS 的 html 和 lxml 的 XML 是因为它 (BS) 更能容忍损坏的 html。 lxml 不能很好地处理损坏的 html。
    猜你喜欢
    • 2016-03-21
    • 2016-11-13
    • 2019-09-08
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    相关资源
    最近更新 更多