pyquery 提取網(wǎng)頁內(nèi)容

from pyquery import PyQuery

html = '''
<head>
    <title>hello</title>
</head>
'''
p = PyQuery(html)
  • html():獲取相應(yīng)的 HTML 塊
p('head').html()
>>> <title>hello</title>
  • text():獲取文本塊
p('head').text()
>>> 'hello'




根據(jù) HTML 標(biāo)簽來獲取元素
from pyquery import PyQuery

html = '''
<div>
    <p>test 1</p>
    <p>test 2</p>
</div>
'''
p = PyQuery(html)
# 獲取所有p標(biāo)簽
p('p')
>>> [<p>, <p>]

print(p('p'))
>>> <p>test 1</p>
    <p>test 2</p>

  • eq: 根據(jù)給定的索引號得到指定元素
# 獲取第一個p標(biāo)簽的內(nèi)容
p('p').eq(0).html()
>>> 'test 1'

# 獲取第二個p標(biāo)簽的內(nèi)容
p('p').eq(1).html()
>>> 'test 2'

# 不用 eq 方法默認(rèn)返回第一個
p('p').html()
>>> 'test 1'




根據(jù)類名、id 名得到指定元素
from pyquery import PyQuery

html = '''
<div>
    <p id='1'>test 1</p>
    <p class='abc'>test 2</p>
</div>
'''
p = PyQuery(html)
  • filter():選擇器
# 返回 id='1' 的p標(biāo)簽內(nèi)容
p('p').filter('#1').html()
>>> 'test 1'

# 返回 class='abc'  的p標(biāo)簽內(nèi)容
p('p').filter('.abc').html()
>>> 'test 2'




查找嵌套元素
from pyquery import PyQuery

html = '''
<div>
    <p id='1'>test 1</p>
    <p class='abc'>test 2</p>
</div>
'''
p = PyQuery(html)
  • find()
# 查找div下的p標(biāo)簽
>>> p('div').find('p')
[<p#1>, <p.abc>]

# 返回div下的第一個p標(biāo)簽內(nèi)容
p('div').find('p').eq(0).html()
>>> 'test 1'




根據(jù)類名、id 名獲取元素
from pyquery import PyQuery

html = '''
<div>
    <p id='1'>test 1</p>
    <p class='abc'>test 2</p>
</div>
'''
p = PyQuery(html)
# 根據(jù)id名獲取元素
p('#1').html()
>>> 'test 1'

# 根據(jù)class名獲取元素
>>> p('.abc').html()
'test 2'




獲取屬性值
from pyquery import PyQuery

html = '''
<p id='my_id'>
    <a >hello</a>
</p>
'''
p = PyQuery(html)
  • attr()
# 獲取a標(biāo)簽的href屬性
p('a').attr('href')
>>> 'http://hello.com'




獲取子元素
from pyquery import PyQuery

html = '''
<span>
    <p id='1'>hello</p>
    <p id='2'>world</p>
</span>
'''
p = PyQuery(html)
  • children()
# 提取div的所有子元素
p.children()
>>> [<p#1>, <p#2>]

# 提取div下id=‘1’的子元素
p.children('#1')
>>> [<p#1>]




獲取父元素
from pyquery import PyQuery

html = '''
<span>
    <p id='1'>hello</p>
    <p id='2'>world</p>
</span>
'''
p = PyQuery(html)
  • parents()
# 提取p標(biāo)簽的父元素
p('p').parents()
>>> [<span>]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、樣式篇 第1章 初識jQuery (1)環(huán)境搭建 進(jìn)入官方網(wǎng)站獲取最新的版本 http://jquery.co...
    凜0_0閱讀 3,673評論 0 44
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評論 19 139
  • 第一章 認(rèn)識jQuery jQuery 能做什么 1. 取得文檔中的元素 2. 修改頁面的外觀 CSS雖然為影響文...
    七弦桐語閱讀 546評論 0 1
  • jQuery基礎(chǔ)(一)——樣式篇 1-2環(huán)境搭建 1-3 jQuery HelloWorld體驗(yàn) $(docume...
    croyance0601閱讀 1,168評論 0 8
  • [TAS]-010 沉默成本 基本法: 算不上什么原創(chuàng), 但是拒絕轉(zhuǎn)載 實(shí)驗(yàn)性文體-仿游戲速攻表演(TAS Too...
    yzhangac閱讀 674評論 0 51

友情鏈接更多精彩內(nèi)容