Python之爬蟲-- XML與XPath

XML

案例1: 

<?xml version="1.0" encoding="utf-8"?>

<bookstore>
    <book category="cooking">
        <title lang="en">Everyday Italian</title>
        <author>Gidada De</author>
        <year>2018</year>
        <price>23</price>
    </book>

    <book category="education">
        <title lang="en">Python is Python</title>
        <author>Food War</author>
        <year>2008</year>
        <price>83</price>
    </book>

    <book category="sport">
        <title lang="en">Running</title>
        <author>Klaus Kuka</author>
        <year>2010</year>
        <price>43</price>
    </book>
	
</bookstore>

XPath(python爬蟲使用XPath解析頁面和提取數據)

一、簡介

       XPath即爲XML路徑語言,它是一種用來確定XML(標準通用標記語言的子集)文檔中某部分位置的語言。XPath基於XML的樹狀結構,有不同類型的節點,包括元素節點,屬性節點和文本節點,提供在數據結構樹中找尋節點的能力。

二、什麼是 XPath?

 

  • XPath(XML Path Language), 是一門在XML文檔中查找信息的語言 
  • XPath 使用路徑表達式在 XML 文檔中進行導航
  • XPath 包含一個標準函數庫
  • XPath 是 XSLT 中的主要元素
  • XPath 是一個 W3C 標準
  • 官方文檔: http://www.w3school.com.cn/xpath/index.asp
  • XPath開發工具:
    • 開元的XPath表達式工具: XMLQuire
    • chrome插件: Xpath Helper
    • Firefox插件: XPath CHecker

三、使用xpath

1、導入模塊

#首先安裝庫 pip install lxml
import lxml
from lxml import etree

2、XPath Helper插件

3、XPath 術語

節點(Node

在 XPath 中,有七種類型的節點:元素、屬性、文本、命名空間、處理指令、註釋以及文檔(根)節點。XML 文檔是被作爲節點樹來對待的。樹的根被稱爲文檔節點或者根節點。

基本值(或稱原子值,Atomic value)

基本值是無父或無子的節點。

項目(Item)

項目是基本值或者節點。

節點關係

父(Parent)

每個元素以及屬性都有一個父。

子(Children)

元素節點可有零個、一個或多個子。

同胞(Sibling)

擁有相同的父的節點

先輩(Ancestor)

某節點的父、父的父,等等。

後代(Descendant)

某個節點的子,子的子,等等

4、選取節點

XPath 使用路徑表達式在 XML 文檔中選取節點。節點是通過沿着路徑或者 step 來選取的。 下面列出了最有用的路徑表達式:

表達式

描述

/

從根節點選取。

// 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置。
. 選取當前節點。
.. 選取當前節點的父節點。
@ 選取屬性。
nodename 選取此節點的所有子節點

案例:

路徑表達式 結果
bookstore 選取 bookstore 元素的所有子節點。
/bookstore 選取根元素 bookstore。註釋:假如路徑起始於正斜槓( / ),則此路徑始終代表到某元素的絕對路徑!
/bookstore/book 選取屬於 bookstore 的子元素的所有 book 元素。
//book 選取所有 book 子元素,而不管它們在文檔中的位置。
bookstore//book 選擇屬於 bookstore 元素的後代的所有 book 元素,而不管它們位於 bookstore 之下的什麼位置。
//@lang 選取名爲 lang 的所有屬性。

5、 謂語(Predicates)

謂語用來查找某個特定的節點,被鑲嵌在方括號中或者包含某個指定的值的節點。在下面的表格中,我們列出了帶有謂語的一些路徑表達式,以及表達式的結果:

路徑表達式 結果
/bookstore/book[1] 選取屬於 bookstore 子元素的第一個 book 元素。
/bookstore/book[last()] 選取屬於 bookstore 子元素的最後一個 book 元素。
/bookstore/book[last()-1] 選取屬於 bookstore 子元素的倒數第二個 book 元素。
/bookstore/book[position()<3] 選取最前面的兩個屬於 bookstore 元素的子元素的 book 元素。
//title[@lang] 選取所有擁有名爲 lang 的屬性的 title 元素。
//title[@lang=’cn’] 選取屬於bookstore下叫book的,含有屬性lang的值是cn的元素。
/bookstore/book[price<90] 選取屬於bookstore下叫book的,含有屬性price的,且值小於90的元素。
/bookstore/book[price<90]/title 選取屬於bookstore下叫book的,含有屬性price的,且值小於90的元素的子元素title。

6、通配符(選取未知節點)

XPath 通配符可用來選取未知的 XML 元素。

通配符 描述
* 匹配任何元素節點。
@* 匹配任何屬性節點。
node() 匹配任何類型的節點。

在下面的表格中,我們列出了一些路徑表達式,以及這些表達式的結果:

路徑表達式 結果
/bookstore/* 選取 bookstore 元素的所有子元素。
//* 選取文檔中的所有元素。
//title[@*] 選取所有帶有屬性的 title 元素。

7、選取多個路徑

通過在路徑表達式中使用”|”運算符,您可以選取若干個路徑。

在下面的表格中,我們列出了一些路徑表達式,以及這些表達式的結果:

路徑表達式 結果
//book/title | //book/author 選取 book 元素的所有 title 和 author元素。
//title | //price 選取文檔中的所有 title 和 price 元素。
/bookstore/book/title | //price 選取屬於 bookstore 元素的 book 元素的所有 title 元素,以及文檔中所有的 price 元素。

8、XPath 實例 

下面是在網上找到的一個小例子。 

import lxml
from lxml import etree

html_doc = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        <li id='l1' class="liClass">1</li>
        <li id='l2'>2</li>
        <li class="liClass">3</li>
        <li id='l4'>4</li>
        <li class="liClass">5</li>
    </ul>

    <div class="liClass">
    </div>
</body>
</html>
'''

mytree = lxml.etree.HTML(html_doc)
# ElementTree object
print(mytree)
print(mytree.xpath('/html/text()'))
print(mytree.xpath('/ul'))
# / 從根元素開始,相當於絕對路徑
print(mytree.xpath('/html/body/ul'))
# // 全局搜索,找到所有
print(mytree.xpath('//li'))
ul = mytree.xpath('//ul')
# . 當前
# 返回的都是列表,查找到所有
li = ul[0].xpath('./li')
print(li)

for l in li:
    # 獲取屬性id的值 @id
    print(l.xpath('./@id'))

# 定位 /標籤[@屬性='值']
liClass = mytree.xpath("//li[@class='liClass']")
print(liClass)
# 判斷,@屬性='值' --->返回True或False
print(mytree.xpath("//li/@id='12'"))
print("===========================")
# 直接使用下標訪問,下標從1開始 獲取對個li裏面的文本
print(mytree.xpath('//li[2]/text()'))
# last()最後一個
print(mytree.xpath('//li[last()]/text()'))
# 倒數第二個
print(mytree.xpath('//li[last()-1]/text()'))
# position() 位置 > < = >= <=
print(mytree.xpath('//li[position()>1]'))
# * 通配
print(mytree.xpath('//*[@class="liClass"]'))
# 或 |
print(mytree.xpath('//li[@class="liClass"] | //div[@class="liClass"]'))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章