【问题标题】:Lxml equivalent for BeautifulSoup find()BeautifulSoup find() 的 Lxml 等效项
【发布时间】:2013-10-02 14:04:21
【问题描述】:

我最近从 Beautifulsoup 切换到 lxml,因为 lxml 可以处理损坏的 HTML,这就是我的情况。我想知道完成 Beautifulsoup find() 的等效形式或程序形式是什么。您在 BS 中看到,我可以通过如下搜索找到树节点:

bs = BeautifulSoup(html)
bs.find('span', {'class': 'some-class-name'})

lxml find() 只是在树上搜索当前层级,如果我想在所有的树节点中搜索呢?

谢谢

【问题讨论】:

    标签: python beautifulsoup lxml


    【解决方案1】:

    你可以使用cssselect:

    root = lxml.html.fromstring(html)
    root.cssselect('span.some-class-name')
    

    xpath:

    root.xpath('.//span[@class="some-class-name"]')
    

    cssselectxpath 方法都返回匹配元素的列表,例如 BeautifulSoup 中的 findAll/find_all 方法。

    【讨论】:

      【解决方案2】:

      如果您不想费心学习 lxmlxpath 表达式的 api,那么这里是另一种选择:

      发件人:http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser

      Beautiful Soup 支持 Python 标准库中包含的 HTML 解析器,但它也支持许多第三方 Python 解析器。一个是 lxml 解析器 [...]

      并指定要使用的特定解析器:

      BeautifulSoup(markup, "lxml")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-08
        • 2012-07-03
        • 2015-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-28
        • 2020-01-01
        相关资源
        最近更新 更多