在Python中的jQuery的HTMLparsing?

有没有任何Python库允许我parsing一个类似于jQuery的HTML文档?

即我想能够使用CSSselect器语法从文档中获取任意一组节点,读取其内容/属性等

我之前使用过的唯一的Python HTMLparsing库就是BeautifulSoup,即使没问题,我一直认为如果我有jQuery语法,parsing会更快。 :d

如果你与BeautifulSoupstream利,你可以添加souplect到你的库。
Soupselect是BeautifulSoup的CSSselect器扩展。

用法:

>>> from BeautifulSoup 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>, ..] 

考虑一下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' 

lxml库支持CSSselect器 。