Python中類似于jquery的pyquery庫(kù)用法分析
本文實(shí)例講述了Python中類似于jquery的pyquery庫(kù)用法。分享給大家供大家參考,具體如下:
pyquery:一個(gè)類似于jquery的Python庫(kù)
pyquery可以使你在xml文檔上做jquery查詢,它的API盡可能地類似于jquery。pyquery使用lxml執(zhí)行快速的xml和html操作。
這并非(至少目前還不是)一個(gè)生成javascript代碼或者與javascript代碼做交互的庫(kù)。pyquery的作者只是由于非常喜歡jquery的API因而將其用python實(shí)現(xiàn)。
該項(xiàng)目目前托管在Github倉(cāng)庫(kù)中并且處于活躍開(kāi)發(fā)狀態(tài)。作者可以為任何想要貢獻(xiàn)源碼的開(kāi)發(fā)者賦予push權(quán)限,并且會(huì)對(duì)其做的變更做回顧。如果你想要貢獻(xiàn)源碼,可以發(fā)Email給項(xiàng)目作者。
項(xiàng)目的Bug可以通過(guò)Github Issue Tracker進(jìn)行提交。
快速入門
你可以使用PyQuery類從一個(gè)字符串,一個(gè)lxml文檔,一個(gè)文件或者一個(gè)url鐘載入一個(gè)xml文檔:
>>> 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=your_url)
>>> d = pq(url=your_url,
... opener=lambda url, **kw: urlopen(url).read())
>>> d = pq(filename=path_to_html_file)
現(xiàn)在,d就相當(dāng)于jquery里的$:
>>> d("#hello")
[<p#hello.hello>]
>>> p = d("#hello")
>>> print(p.html())
Hello world !
>>> p.html("you know <a >Python</a> rocks")
[<p#hello.hello>]
>>> print(p.html())
you know <a rel="external nofollow" >Python</a> rocks
>>> print(p.text())
you know Python rocks
你也可以使用某些jQuery中可用而并非css標(biāo)準(zhǔn)的偽類,諸如 :first :last :even :odd :eq :lt :gt :checked :selected :file:等
>>> d('p:first')
[<p#hello.hello>]
參見(jiàn)http://pyquery.rtfd.org/查看全部文檔
CSS
你可以像這樣添加、切換、移除CSS:
>>> p.addClass("toto")
[<p#hello.hello.toto>]
>>> p.toggleClass("titi toto")
[<p#hello.hello.titi>]
>>> p.removeClass("titi")
[<p#hello.hello>]
或者操作CSS樣式:
>>> p.css("font-size", "15px")
[<p#hello.hello>]
>>> p.attr("style")
'font-size: 15px'
>>> p.css({"font-size": "17px"})
[<p#hello.hello>]
>>> p.attr("style")
'font-size: 17px'
使用更加Pythonic的方式完成同樣的功能 (‘_' 字符轉(zhuǎn)換為 ‘-‘):
>>> p.css.font_size = "16px"
>>> p.attr.style
'font-size: 16px'
>>> p.css['font-size'] = "15px"
>>> p.attr.style
'font-size: 15px'
>>> p.css(font_size="16px")
[<p#hello.hello>]
>>> p.attr.style
'font-size: 16px'
>>> p.css = {"font-size": "17px"}
>>> p.attr.style
'font-size: 17px'
使用偽類:
- :button
匹配所有按鈕輸入元素和按鈕元素 Matches all button input elements and the button element
- :checkbox
匹配所有復(fù)選框輸入元素 Matches all checkbox input elements
- :checked
匹配選中的元素,下標(biāo)從0開(kāi)始 Matches odd elements, zero-indexed
- :child
右邊是左邊的直接子元素 right is an immediate child of left
- :contains()
包含元素 Matches all elements that contain the given text
- :descendant
右邊是左邊的子元素、孫元素或者更遠(yuǎn)的后繼元素 right is a child, grand-child or further descendant of left
- :disabled
匹配所有被禁用的元素 Matches all elements that are disabled
- :empty
匹配所有不包括任何其他元素的元素 Match all elements that do not contain other elements
- :enabled
匹配所有啟用的元素 Matches all elements that are enabled
- :eq()
使用下標(biāo)匹配 Matches a single element by its index
- :even
從下標(biāo)0開(kāi)始,匹配所有偶數(shù)元素 Matches even elements, zero-indexed
- :file
匹配所有文件類型的輸入元素 Matches all input elements of type file
- :first
匹配第一個(gè)被選擇的元素 Matches the first selected element
- :gt()
匹配下標(biāo)大于指定值的元素 Matches all elements with an index over the given one
- :header
匹配所有標(biāo)題元素 Matches all header elelements (h1, ..., h6)
- :image
匹配所有圖像輸入元素 Matches all image input elements
- :input
匹配所有輸入元素 Matches all input elements
- :last
匹配最后一個(gè)選擇的元素 Matches the last selected element
- :lt()
匹配所有下標(biāo)小于指定值的元素 Matches all elements with an index below the given one
- :odd
匹配奇元素,下標(biāo)從0開(kāi)始 Matches odd elements, zero-indexed
- :parent
匹配所有包含其他元素的元素 Match all elements that contain other elements
- :password
匹配所有密碼輸入元素 Matches all password input elements
- :radio
匹配單選按鈕輸入元素 Matches all radio input elements
- :reset
匹配所有重置輸入元素 Matches all reset input elements
- :selected
匹配所有被選中的元素 Matches all elements that are selected
- :submit
匹配所有提交輸入元素 Matches all submit input elements
- :text¶
匹配所有文本輸入元素 Matches all text input elements
操作
你也可以向標(biāo)簽的尾部追加元素:
>>> d = pq('<p class="hello" id="hello">you know Python rocks</p>')
>>> d('p').append(' check out <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span>reddit</span></a>')
[<p#hello.hello>]
>>> print(d)
<p class="hello" id="hello">you know Python rocks check out <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span>reddit</span></a></p>
或者加至開(kāi)頭:
>>> p = d('p')
>>> p.prepend('check out <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >reddit</a>')
[<p#hello.hello>]
>>> print(p.html())
check out <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >reddit</a>you know ...
在其他元素之前或者之后追加元素:
>>> d = pq('<html><body><div id="test"><a rel="external nofollow" rel="external nofollow" >python</a> !</div></body></html>')
>>> p.prependTo(d('#test'))
[<p#hello.hello>]
>>> print(d('#test').html())
<p class="hello" ...
在其他元素之后插入元素:
>>> p.insertAfter(d('#test'))
[<p#hello.hello>]
>>> print(d('#test').html())
<a rel="external nofollow" rel="external nofollow" >python</a> !
或者插入其他元素之前:
>>> p.insertBefore(d('#test'))
[<p#hello.hello>]
>>> print(d('body').html())
<p class="hello" id="hello">...
對(duì)每個(gè)元素做一些事情:
>>> p.each(lambda i, e: pq(e).addClass('hello2'))
[<p#hello.hello.hello2>]
移除一個(gè)元素:
>>> d = pq('<html><body><p id="id">Yeah!</p><p>python rocks !</p></div></html>')
>>> d.remove('p#id')
[<html>]
>>> d('p#id')
[]
移除選中元素的內(nèi)容:
>>> d('p').empty()
[<p>]
你可以獲得修改后的html內(nèi)容:
>>> print(d) <html><body><p/></body></html>
你可以生成html片段:
>>> from pyquery import PyQuery as pq
>>> print(pq('<div>Yeah !</div>').addClass('myclass') + pq('<b>cool</b>'))
<div class="myclass">Yeah !</div><b>cool</b>
移除所有命名空間:
>>> d = pq('<foo xmlns="http://example.com/foo"></foo>')
>>> d
[<{http://example.com/foo}foo>]
>>> d.remove_namespaces()
[<foo>]
遍歷
一些jQuery遍歷方法也可以支持。這里有幾個(gè)例子。
你可以使用字符串選擇器過(guò)濾選擇列表:
>>> d = pq('<p id="hello" class="hello"><a/></p><p id="test"><a/></p>')
>>> d('p').filter('.hello')
[<p#hello.hello>]
可以使用eq選擇器選中單個(gè)元素:
>>> d('p').eq(0)
[<p#hello.hello>]
你可以找出嵌套元素:
>>> d('p').find('a')
[<a>, <a>]
>>> d('p').eq(1).find('a')
[<a>]
也支持使用end從一級(jí)遍歷中跳出:
>>> d('p').find('a').end()
[<p#hello.hello>, <p#test>]
>>> d('p').eq(0).end()
[<p#hello.hello>, <p#test>]
>>> d('p').filter(lambda i: i == 1).end()
[<p#hello.hello>, <p#test>]
網(wǎng)絡(luò) Scraping
pyquery也可以從一個(gè)url載入html文檔:
>>> pq(your_url) [<html>]
缺省使用的是python的urllib。
如果安裝了requests就使用requests。你可以使用大部分requests的參數(shù)。
>>> pq(your_url, headers={'user-agent': 'pyquery'})
[<html>]
>>> pq(your_url, {'q': 'foo'}, method='post', verify=True)
[<html>]
pyquery – PyQuery完整API參見(jiàn):http://pyquery.readthedocs.org/en/latest/api.html
pyquery.ajax – PyQuery AJAX 擴(kuò)展
如果安裝了WebOb(它并不是pyquery的依賴項(xiàng)目),你可以查詢一些wsgi app。在本例中,測(cè)試app在/處返回一個(gè)簡(jiǎn)單的輸入,在/submit處返回一個(gè)提交按鈕: IN this example the test app returns a simple input at / and a submit button at /submit:
>>> d = pq('<form></form>', app=input_app)
>>> d.append(d.get('/'))
[<form>]
>>> print(d)
<form><input name="youyou" type="text" value=""/></form>
app在新節(jié)點(diǎn)中也可用: The app is also available in new nodes:
>>> d.get('/').app is d.app is d('form').app
True
你也可以請(qǐng)求另外一個(gè)路徑:
>>> d.append(d.get('/submit'))
[<form>]
>>> print(d)
<form><input name="youyou" type="text" value=""/><input type="submit" value="OK"/></form>
如果安裝了restkit,你就可以直接從一個(gè)HostProxy app獲取url:
>>> a = d.get(your_url) >>> a [<html>]
你可以獲取到app的響應(yīng):
>>> print(a.response.status) 200 OK
小貼士 Tips
你可以使鏈接轉(zhuǎn)化為絕對(duì)鏈,在屏幕抓取時(shí)還會(huì)比較有用: You can make links absolute which can be usefull for screen scrapping:
>>> d = pq(url=your_url, parser='html')
>>> d('form').attr('action')
'/form-submit'
>>> d.make_links_absolute()
[<html>]
使用不同的解析器
缺省情況下,pyquery使用lxml xml解析器并且如果它不能工作的話,繼續(xù)嘗試lxml.html中的html解析器。xml解析器在解析xhtml頁(yè)面時(shí)可能出現(xiàn)一些問(wèn)題,因?yàn)榻馕銎鞑粫?huì)拋出一個(gè)錯(cuò)誤,而是給出一個(gè)不能用的樹(shù)。 The xml parser can sometimes be problematic when parsing xhtml pages because the parser will not raise an error but give an unusable tree (on w3c.org for example).
你也可以顯式地聲明使用哪一個(gè)解析器:
>>> pq('<html><body><p>toto</p></body></html>', parser='xml')
[<html>]
>>> pq('<html><body><p>toto</p></body></html>', parser='html')
[<html>]
>>> pq('<html><body><p>toto</p></body></html>', parser='html_fragments')
[<p>]
html和html_fragments解析器都在lxml.html當(dāng)中。
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
- Python Pandas pandas.read_sql_query函數(shù)實(shí)例用法分析
- python中pandas操作apply返回多列的實(shí)現(xiàn)
- python?pandas創(chuàng)建多層索引MultiIndex的6種方式
- Python+pandas編寫命令行腳本操作excel的tips詳情
- Python Pandas實(shí)現(xiàn)DataFrame合并的圖文教程
- Python的Django框架實(shí)現(xiàn)數(shù)據(jù)庫(kù)查詢(不返回QuerySet的方法)
- python實(shí)現(xiàn)合并多個(gè)list及合并多個(gè)django QuerySet的方法示例
- python?pandas?query的使用方法
相關(guān)文章
Python Selenium常見(jiàn)的報(bào)錯(cuò)問(wèn)題以及措施
這篇文章主要介紹了Python Selenium常見(jiàn)的報(bào)錯(cuò)問(wèn)題以及措施,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
Python 如何實(shí)現(xiàn)文件自動(dòng)去重
這篇文章主要介紹了Python 實(shí)現(xiàn)文件自動(dòng)去重操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
vscode搭建之python?Django環(huán)境配置方式
這篇文章主要介紹了vscode搭建之python?Django環(huán)境配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01
python實(shí)現(xiàn)將一維列表轉(zhuǎn)換為多維列表(numpy+reshape)
今天小編就為大家分享一篇python實(shí)現(xiàn)將一維列表轉(zhuǎn)換為多維列表(numpy+reshape),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
Flask web開(kāi)發(fā)處理POST請(qǐng)求實(shí)現(xiàn)(登錄案例)
這篇文章主要介紹了Flask web開(kāi)發(fā)處理POST請(qǐng)求實(shí)現(xiàn)(登錄案例),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
PyTorch CUDA環(huán)境配置及安裝的步驟(圖文教程)
這篇文章主要介紹了PyTorch CUDA環(huán)境配置及安裝的步驟(圖文教程),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Python中np.linalg.norm()用法實(shí)例總結(jié)
在線性代數(shù)中一個(gè)向量通過(guò)矩陣轉(zhuǎn)換成另一個(gè)向量時(shí),原有向量的大小就是向量的范數(shù),這個(gè)變化過(guò)程的大小就是矩陣的范數(shù),下面這篇文章主要給大家介紹了關(guān)于Python中np.linalg.norm()用法的相關(guān)資料,需要的朋友可以參考下2022-07-07

