原文連接:http://www.nnzhp.cn/archives/630
PyQuery模塊也是一個(gè)解析html的一個(gè)模塊滔悉,它和Beautiful Soup用起來(lái)差不多醋安,它是jquery實(shí)現(xiàn)的借杰,和jquery語(yǔ)法差不多斩箫,會(huì)用jquery的人用起來(lái)就比較方便了里伯。
Pyquery需要依賴(lài)lxml模塊含思,不裝的話崎弃,使用會(huì)報(bào)錯(cuò)。
安裝
pip install lxml
pip install pyquery
解析html的3種方式
from pyquery import PyQuery
html = """
<html><head><title>BestTest</title></head>
<body>
<div>
<p class="content">最專(zhuān)業(yè)的軟件測(cè)試培訓(xùn)
<a class="link" id="link1"><!--首頁(yè)--></a>,
<a class="link" id="link2">BestTest性能測(cè)試</a> and
<a class="link" id="link3" target="_blank">BestTest自動(dòng)化測(cè)試</a>;
課程詳情請(qǐng)點(diǎn)擊上面的鏈接.</p>
<p class="content">.這是廣告植入.</p>
<p class="title">BestTest is best</p>
</div>
</body>
</html>
"""
# 解析html的3種方式
doc = PyQuery(url='http://www.nnzhp.cn') #指定url
doc2 = PyQuery(html) #指定html字符串
doc3 = PyQuery(filename='index.html') #指定文件
print(doc)
print(doc2)
print(doc3)
css選擇器
css在bs模塊里面也用過(guò)含潘,用法差不多饲做。具體如下
# css選擇器
print(doc2('.link')) #通過(guò)class
print(doc2('#link1')) #通過(guò)id
print(doc2('.content,#link1')) #找到所有class為content和id為link1的
print(doc2('.content #link1')) #在content下面找到id為link1的元素
print(doc2('a'))#找到所有的a標(biāo)簽
print(doc2('[href]'))#找到所有帶有href屬性的元素
print(doc2('a[target=_blank]')#找到a標(biāo)簽下面target為_(kāi)blank的
常用方法
eq方法,獲取第幾個(gè)元素
a_tags = doc2('a')
print(a_tags.eq(0))#a標(biāo)簽里面第一個(gè)
print(a_tags.eq(1))#a標(biāo)簽里面第二個(gè)
# items()
#如果找到多個(gè)元素的話遏弱,想循環(huán)取元素的話盆均,就得用.items()方法,items就是為了循環(huán)用的
a_tag = doc2('a')
for a in a_tag.items():
print(a.text())
# text() 腾窝、html()
#text()方法是獲取元素里面的文字的缀踪,html()是獲取元素的html
a=doc2('.content')
print(a.html()) #html格式的
print(a.text()) #只有里面的文字
#find方法,查找元素
print(doc2.find('p').find('a'))#從所有的p標(biāo)簽里面找到a標(biāo)簽
print(doc2.find('p'))#找到所有的p標(biāo)簽
print(doc2.find('.content'))#找到所有class為content的
#filter方法虹脯,用來(lái)篩選
print(doc2.find('a').filter('#link1')) #先找到a標(biāo)簽驴娃,然后從a標(biāo)簽里面篩選出來(lái)id為link1的
#attr方法,獲取屬性
print(doc2('#link1').attr(('href')))#獲取id為link1的href的屬性值
個(gè)人新增
In [103]: html='''<a class="a1_test" id="link1">home</a>,
.....: <a class="a2_test test" id="link2">BestTest</a>
.....: <div class="div_test">
.....: <div>div test</div>
.....: <span>span test1</span>
.....: <span>span test2</span>
.....: </div>
.....: '''
In [104]: doc=PyQuery(html)
對(duì)于class有多個(gè)屬性的選擇
In [107]: doc('.a2_test.test')
Out[107]: [<a#link2.a2_test.test>]
標(biāo)簽嵌套獲取(子標(biāo)簽)
In [110]: doc('.div_test > div')
Out[110]: [<div>]
In [111]: doc('.div_test > div').text()
Out[111]: 'div test'
標(biāo)簽嵌套有相同的標(biāo)簽(子標(biāo)簽)
In [112]: doc('.div_test > span')
Out[112]: [<span>, <span>]
In [113]: doc('.div_test > span').eq(0).text()
Out[113]: 'span test1'