pyquery標籤選擇
獲取了所有的img標籤(css選擇器,你也可以換成不同的class和id)
1view codeimport
requests
2importre3
from pyquery import
pyquery as pq
4 headers=
11 response=requests.get('
',headers=headers,timeout=9)
12 doc=pq(response.content)13#
css選擇器
14 a=doc('
img')#
15print(a)
url初始化(通過訪問url得到html**)
有了pyquery,你甚至不需要再使用requests來get網頁
from pyquery import檔案初始化(通過檔案得到html**)pyquery as pq
headers=
doc=pq(url='
',headers=headers)
#直接初始化url得到源**
print(doc('
title
').text())
#css選擇器檔案初始化
from pyquery import
pyquery as pq
import
requests
#寫檔案
#headers=
#result=requests.get('',headers=headers)
## result=pq(url='',headers=headers)
#print(type(result))
#with open("zhihu.html",'wb')as f:
#f.write(result.content)
#讀檔案
doc=pq(filename='
test.html')
print(doc('
title
'))
doc('查詢元素#content .list li
')#得到的是所有的符合這種層級關係的li
子元素find(查內部的元素)
html=『.....』children(和find一樣)doc=py(html)
a=doc('
.content')
b=a.find('
img')查詢.content內的img標籤
html=『.....』父元素doc=py(html)
a=doc('
.content')
b=a.children('
img')查詢.content內的img標籤
html=『.....』doc=py(html)
a=doc('
.content')
b=a.parent()查詢.content的父元素整體
html=『.....』當然也可以加上css選擇器doc=py(html)
a=doc('
.content')
b=a.parents()遍歷輸出.content的所有祖先元素整體
html=『.....』兄弟元素doc=py(html)
a=doc('
.content')
b=a.parents(『.wrap』)查詢.content的祖先節點中為.wrap的標籤
html=『.....』遍歷查詢的元素doc=py(html)
a=doc('
.content')
b=a.siblings()#
查詢.content的同級標籤,也可以加css選擇器
from pyquery importpyquery as pq
headers=
doc=pq(url='
',headers=headers)
a=doc('
img').items()#
得到可迭代物件
for i in
a:
print(i)
<加入i是得到的上述的html元素img
src="data:image/svg+xml;utf8,"
data-rawwidth
="503"
data-rawheight
="410"
class
="origin_image zh-lightbox-thumb lazy"
width
="503"
data-original
=""data-actualsrc
=""/>
獲取屬性:jpgurl=i.attr('data-original')
獲取文字:text=i.text()
獲取html:html=i.html()//獲取i裡面的html元素
dom操作
addclass(新增class)、removeclass(移除class)
attr: .attr('name':'userid')//新增或替換name屬性
css: .css('height':'500px')//新增或替換style
PyQuery庫的使用
html from pyquery import pyquery as pq doc pq html print doc print type doc print doc li 由於pyquery寫起來比較麻煩,所以我們匯入的時候都會新增別名 from pyquery import pyquery ...
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...