【问题标题】:jquery-like HTML parsing in Python?在 Python 中进行类似 jquery 的 HTML 解析?
【发布时间】:2011-03-04 08:06:52
【问题描述】:

是否有任何 Python 库可以让我解析类似于 jQuery 的 HTML 文档?

即我希望能够使用 CSS 选择器语法 从文档中抓取任意一组节点,读取它们的内容/属性等。

我以前使用过的唯一 Python HTML 解析库是 BeautifulSoup,尽管它很好,但我一直认为如果我有可用的 jQuery 语法,我的解析会更快。 :D

【问题讨论】:

标签: python jquery css-selectors html-parsing


【解决方案1】:

lxml 库支持CSS selectors

【讨论】:

    【解决方案2】:

    如果您精通BeautifulSoup,您可以将soupselect 添加到您的库中。
    Soupselect 是 BeautifulSoup 的 CSS 选择器扩展。

    用法:

    from bs4 import BeautifulSoup as Soup
    from soupselect import select
    import urllib
    soup = Soup(urllib.urlopen('http://slashdot.org/'))
    select(soup, 'div.title h3')
    
        [<h3><span><a href='//science.slashdot.org/'>Science</a>:</span></h3>,
         <h3><a href='//slashdot.org/articles/07/02/28/0120220.shtml'>Star Trek</h3>,
        ..]
    

    【讨论】:

    • 这听起来对我来说是最好的解决方案,我会试一试。谢谢!
    • 美丽汤4现在是from bs4
    • 如果你安装soupselect有问题,你应该试试她提供的pip兼容版本github.com/syabro/soupselect:sudo pip install https://github.com/syabro/soupselect/archive/master.zip
    • 顺便提一下,Beautiful Soup 4 已经包含了内置对 CSS 选择器的支持的 soupselect 项目。请参阅release note
    【解决方案3】:

    考虑 PyQuery:

    http://packages.python.org/pyquery/

    >>> from pyquery import PyQuery as pq
    >>> from lxml import etree
    >>> import urllib
    >>> d = pq("<html></html>")
    >>> d = pq(etree.fromstring("<html></html>"))
    >>> d = pq(url='http://google.com/')
    >>> d = pq(url='http://google.com/', opener=lambda url: urllib.urlopen(url).read())
    >>> d = pq(filename=path_to_html_file)
    >>> d("#hello")
    [<p#hello.hello>]
    >>> p = d("#hello")
    >>> p.html()
    'Hello world !'
    >>> p.html("you know <a href='http://python.org/'>Python</a> rocks")
    [<p#hello.hello>]
    >>> p.html()
    u'you know <a href="http://python.org/">Python</a> rocks'
    >>> p.text()
    'you know Python rocks'
    

    【讨论】:

      【解决方案4】:

      BeautifulSoup,现在支持 css selectors

      import requests
      from bs4 import BeautifulSoup as Soup
      html = requests.get('https://stackoverflow.com/questions/3051295').content
      soup = Soup(html)
      

      这个问题的标题

      soup.select('h1.grid--cell :first-child')[0].text
      

      问题点赞数

      # first item 
      soup.select_one('[itemprop="upvoteCount"]').text
      

      使用Python Requests获取html页面

      【讨论】:

        猜你喜欢
        • 2012-04-06
        • 1970-01-01
        • 1970-01-01
        • 2014-10-26
        • 2013-11-02
        • 1970-01-01
        • 1970-01-01
        • 2010-10-21
        • 2011-05-24
        相关资源
        最近更新 更多