1. 程式人生 > >python解析HTML之:PyQuery庫的介紹與使用

python解析HTML之:PyQuery庫的介紹與使用

att 用法 hello ext dom 的人 inf 目標 title

本篇大部分轉載於https://www.jianshu.com/p/c07f7cd1b548

先放自已自己解析techweb一個網站圖片的代碼

from pyquery import PyQuery as pq

headers = {User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 
                         (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36}

def get_info(url):
    html = requests.get(url,headers =headers,verify=False)
    d 
= pq(html.content) doc = d("div").filter(".list_con") doc = doc("div").filter(".picture_text") for tr in doc.items(): temp =tr.find("img") print(temp.attr("src")) if __name__ == "__main__": get_info("http://mi.techweb.com.cn/")

前言

Python關於爬蟲的庫挺多的,也各有所長。了解前端的也都知道, jQuery 能夠通過選擇器精確定位 DOM 樹中的目標並進行操作,所以我想如果能用 jQuery 去爬網頁那就 cool 了。

就搜了下看 Python 有沒有與 DOM 相關的庫什麽的,還真找到了—— PyQuery

PyQuery簡介

pyquery相當於jQuery的python實現,可以用於解析HTML網頁等。它的語法與jQuery幾乎完全相同,對於使用過jQuery的人來說很熟悉,也很好上手。

引用作者的原話就是:

“The API is as much as possible the similar to jquery.” 。

安裝

使用 pip 或者 easy_install 都可以。
註意:由於 pyquery 依賴於 lxml ,要先安裝 lxml ,否則會提示失敗。

  1. 安裝lxml:https://pypi.python.org/pypi/lxml/2.3/ (建議直接下載安裝包,方便快捷);
  2. 安裝pyquery:easy_install pyquery 或者pip install pyquery;
  3. 驗證:輸入 import pyquery 回車不報錯即安裝成功;

初始化

有 4 種方法可以進行初始化:
可以通過傳入 字符串、lxml、文件 或者 url 來使用PyQuery。

from pyquery import PyQuery as pq
from lxml import etree

d = pq("<html></html>")#傳入字符串
d = pq(etree.fromstring("<html></html>"))#傳入lxml
d = pq(url=‘http://google.com/‘) #傳入url
d = pq(filename=path_to_html_file) #傳入文件

現在,d 就像 jQuery 中的 $ 一樣了。

示例

通過一個簡單的例子快速熟悉 pyquery 的用法,傳入文件 example.html,內容如下:

<div>
<tr class="item-0">
<td>first section</td>
<td>1111</td>
<td>17-01-28 22:51</td>
</tr>
<tr class="item-1">
<td>second section</td>
<td>2222</td>
<td>17-01-28 22:53</td>
</tr>
</div>

python 程序:

# -*- coding: utf-8 -*-
from pyquery import PyQuery as pq#引入 PyQuery

doc = pq(filename=‘example.html‘)# 傳入文件 example.html

print doc.html() # html()方法獲取當前選中的 html 塊

print doc(‘.item-1‘) # 相當於 class 選擇器,選取 class 為 item-1 的 html 塊

data = doc(‘tr‘) # 選取 <tr> 元素

for tr in data.items():# 遍歷 data 中的 <tr> 元素
temp = tr(‘td‘).eq(2).text() # 選取第3個 <td> 元素中的文本塊
print temp

運行結果:

# print doc.html()
<tr class="item-0">
<td>first section</td>
<td>1111</td>
<td>17-01-28 22:51</td>
</tr>
<tr class="item-1">
<td>second section</td>
<td>2222</td>
<td>17-01-28 22:53</td>
</tr>

# print doc(‘.item-1‘)
<tr class="item-1">
<td>second section</td>
<td>2222</td>
<td>17-01-28 22:53</td>
</tr>

# print tr(‘td‘).eq(2).text()
17-01-28 22:51
# print tr(‘td‘).eq(2).text()
17-01-28 22:53

操作

1、.html().text():獲取相應的 HTML 塊或者文本內容,

p=pq("<head><title>Hello World!</title></head>")

print p(‘head‘).html()# 獲取相應的 HTML 塊
print p(‘head‘).text()# 獲取相應的文本內容

‘‘‘輸出:
<title>hello</title>
Hello World!
‘‘‘

2、.(‘selector‘):通過選擇器來獲取目標內容,

d = pq("<div><p id=‘item-0‘>test 1</p><p class=‘item-1‘>test 2</p></div>")

print d(‘div‘).html()# 獲取 <div> 元素內的 HTML 塊
print d(‘#item-0‘).text()# 獲取 id 為 item-0 的元素內的文本內容
print d(‘.item-1‘).text()# 獲取 class 為 item-1 的元素的文本內容

‘‘‘輸出:
<p id="item-0">test 1</p><p class="item-1">test 2</p>
test 1
test 2
‘‘‘

3、.eq(index):根據索引號獲取指定元素(index 從 0 開始),

d = pq("<div><p id=‘item-0‘>test 1</p><p class=‘item-1‘>test 2</p></div>")

print d(‘p‘).eq(1).text()# 獲取第二個 p 元素的文本內容,

‘‘‘輸出
test 2
‘‘‘

4、.find():查找嵌套元素,

d = pq("<div><p id=‘item-0‘>test 1</p><p class=‘item-1‘>test 2</p></div>")

print d(‘div‘).find(‘p‘) # 查找 <div> 內的 p 元素
print d(‘div‘).find(‘p‘).eq(0) # 查找 <div> 內的 p 元素,輸出第一個 p 元素

‘‘‘輸出:
<p id="item-0">test 1</p><p class="item-1">test 2</p>
<p id="item-0">test 1</p>
‘‘‘

5、.filter():根據 class、id 篩選指定元素,

d = pq("<div><p id=‘item-0‘>test 1</p><p class=‘item-1‘>test 2</p></div>")

print d(‘p‘).filter(‘.item-1‘) # 查找 class 為 item-1 的 p 元素
print d(‘p‘).filter(‘#item-0‘) # 查找 id 為 item-0 的 p 元素

‘‘‘輸出:
<p class="item-1">test 2</p>
<p id="item-0">test 1</p>
‘‘‘

6、.attr():獲取、修改屬性值,

d = pq("<div><p id=‘item-0‘>test 1</p><a class=‘item-1‘>test 2</p></div>")

print d(‘p‘).attr(‘id‘) # 獲取 <p> 標簽的屬性 id
print d(‘a‘).attr(‘class‘,‘new‘)# 修改 <a> 標簽的 class 屬性為 new

‘‘‘輸出:
item-0
<a class="new">test 2</a>
‘‘‘

7、其他操作:
.addClass(value):添加 class;
.hasClass(name):判斷是否包含指定的 class,返回 True 或 False;
.children():獲取子元素;
.parents():獲取父元素;
.next():獲取下一個元素;
.nextAll():獲取後面全部元素塊;
.not_(‘selector‘):獲取所有不匹配該選擇器的元素;
for i in d.items(‘li‘): print i.text():遍歷 d 中的 li 元素;

結語

以上的操作對於日常爬取一些小數據資料,基本足夠使用了。當然,PyQuery 還有很多其他內容,這裏就不做說明了,如果需要了解更多關於 PyQuery 的內容的可以去查看官方文檔。

官方文檔是英文的,但也比較容易閱讀和理解。我找到了一個中文的教程網站,這裏也提供出來。

官方文檔:https://pythonhosted.org/pyquery/index.html#
中文教程:http://www.geoinformatics.cn/lab/pyquery/

python解析HTML之:PyQuery庫的介紹與使用