PyQuery庫的使用

2022-09-01 02:45:09 字數 3908 閱讀 5999

html = '''

'''from pyquery import

pyquery as pq

doc =pq(html)

print

(doc)

print

(type(doc))

print(doc('

li'))

由於pyquery寫起來比較麻煩,所以我們匯入的時候都會新增別名:

from pyquery import pyquery as pq

這裡我們可以知道上述**中的doc其實就是乙個pyquery物件,我們可以通過doc可以進行元素的選擇,其實這裡就是乙個css選擇器,

所以css選擇器的規則都可以用,直接doc(標籤名)就可以獲取所有的該標籤的內容,

如果想要獲取class 則doc('.class_name'),如果是id則doc('#id_name')....

from pyquery import

pyquery as pq

doc = pq(url="

",encoding='

utf-8')

print(doc('

head

'))

html = '''

'''from pyquery import

pyquery as pq

doc =pq(html)

print(doc('

#container .list li

')) #

選擇最裡層的

parent與parents區別乙個是父節點,乙個是父節點和祖先節點

print

(type(parents))

print(parents)

兄弟元素siblings
html = '''

'''from pyquery import

pyquery as pq

doc =pq(html)

li = doc('

.list .item-0.active')

print(li.siblings())

html = '''

'''from pyquery import

pyquery as pq

doc =pq(html)

li = doc('

.item-0.active')

#print(li)

lis = doc('

li').items() #

生成器,存了所有的li

#print(type(lis))

for li in

lis:

print

(type(li))

print(li)

html = '''

'''from pyquery import

pyquery as pq

doc =pq(html)

a = doc('

.item-0.active a')

print

(a)print(a.attr('

href'))

print(a.attr.href)

html = '''

'''from pyquery import

pyquery as pq

doc =pq(html)

a = doc('

.item-0.active a')

print

(a)print(a.text())

html = '''

'''from pyquery import

pyquery as pq

doc =pq(html)

li = doc('

.item-0.active')

print

(li)

print(li.html()) #

結果為li標籤裡面的 third item

html = '''

'''from pyquery import

pyquery as pq

doc =pq(html)

li = doc('

.item-0.active')

print

(li)

li.removeclass(

'active')

print

(li)

li.addclass(

'active')

print(li)

html = '''

'''from pyquery import

pyquery as pq

doc =pq(html)

li = doc('

.item-0.active')

print

(li)

li.attr(

'name

', '

link')

print

(li)

li.css(

'font-size

', '

14px')

print(li)

html = '''

hello, world

this is a paragraph.

'''from pyquery import

pyquery as pq

doc =pq(html)

wrap = doc('

.wrap')

print

(wrap.text())

wrap.find('p

').remove()

print(wrap.text())

pyquery庫的使用

pyquery標籤選擇 獲取了所有的img標籤 css選擇器,你也可以換成不同的class和id 1 import requests 2importre3 from pyquery import pyquery as pq 4 headers 11 response requests.get hea...

PyQuery庫的使用(下篇)

3.41 單個元素輸出 html 清空 from pyquery import pyquery doc pyquery html print doc input 輸出input標籤 3.42 遍歷元素輸出 html 清空 from pyquery import pyquery doc pyquery...

Python中PyQuery庫的使用

pyquery庫是jquery的python實現,可以用於解析html網頁內容,我個人寫過的一些抓取網頁資料的指令碼就是用它來解析html獲取資料的。它的官方文件位址是 今天重新看了一遍整個文件,把它的一些使用方法整理了一下,做個記錄。使用方法 from pyquery import pyquery...