PYTHON PYQUERY 基本用法
阿新 • • 發佈:2018-09-29
pyquery tro 遍歷 python color img style att ref
引用方法
from pyquery import PyQuery as pqView Code
基本CSS選擇器
from pyquery import PyQuery as pq html = ‘‘‘ <div id="wrap"> <ul class="s_from"> asdasd <link href="http://asda.com">asdadasdad12312</link> <link href="http://asda1.com">asdadasdad12312</link> <link href="http://asda2.com">asdadasdad12312</link> </ul> </div>View Code‘‘‘ doc = pq(html) print doc("#wrap .s_from link")
運行結果
<link href="http://asda.com">asdadasdad12312</link> <link href="http://asda1.com">asdadasdad12312</link> <link href="http://asda2.com">asdadasdad12312</link>View Code
#是查找id的標簽 .是查找class 的標簽 link 是查找link 標簽 中間的空格表示裏層
遍歷查找結果
from pyquery import PyQuery as pq html = ‘‘‘ <div href="wrap"> hello nihao <ul class="s_from"> asdasd <link class=‘active1 a123‘ href="http://asda.com">asdadasdad12312</link> <link class=‘active2‘ href="http://asda1.com">asdadasdad12312</link> <link class=‘movie1‘ href="http://asda2.com">asdadasdad12312</link> </ul> </div>View Code‘‘‘ doc = pq(html) its=doc("link").items() for it in its: print(it)
運行結果
<link class="active1 a123" href="http://asda.com">asdadasdad12312</link> <link class="active2" href="http://asda1.com">asdadasdad12312</link> <link class="movie1" href="http://asda2.com">asdadasdad12312</link>View Code
獲取屬性信息
from pyquery import PyQuery as pq html = ‘‘‘ <div href="wrap"> hello nihao <ul class="s_from"> asdasd <link class=‘active1 a123‘ href="http://asda.com">asdadasdad12312</link> <link class=‘active2‘ href="http://asda1.com">asdadasdad12312</link> <link class=‘movie1‘ href="http://asda2.com">asdadasdad12312</link> </ul> </div> ‘‘‘ doc = pq(html) its=doc("link").items() for it in its: print(it.attr(‘href‘)) print(it.attr.href)View Code
運行結果
http://asda.com http://asda.com http://asda1.com http://asda1.com http://asda2.com http://asda2.comView Code
獲取文本
from pyquery import PyQuery as pq html = ‘‘‘ <div href="wrap"> hello nihao <ul class="s_from"> asdasd <link class=‘active1 a123‘ href="http://asda.com">asdadasdad12312</link> <link class=‘active2‘ href="http://asda1.com">asdadasdad12312</link> <link class=‘movie1‘ href="http://asda2.com">asdadasdad12312</link> </ul> </div> ‘‘‘ doc = pq(html) its=doc("link").items() for it in its: print(it.text())View Code
運行結果
asdadasdad12312
asdadasdad12312
asdadasdad12312
View Code
PYTHON PYQUERY 基本用法