1. 程式人生 > >PYTHON PYQUERY 基本用法

PYTHON PYQUERY 基本用法

pyquery tro 遍歷 python color img style att ref

引用方法

技術分享圖片
from pyquery import PyQuery as pq
View 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>
‘‘‘ doc = pq(html) print doc("#wrap .s_from link")
View Code

運行結果

技術分享圖片
<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>
‘‘‘ doc = pq(html) its=doc("link").items() for it in its: print(it)
View Code

運行結果

技術分享圖片
<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.com
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.text())
View Code

運行結果

技術分享圖片
asdadasdad12312
asdadasdad12312
asdadasdad12312
View Code

PYTHON PYQUERY 基本用法