4,xpath獲取數據


xpath

XPath 使用路徑表達式在 XML 文檔中進行導航.

XPath 使用路徑表達式來選取 XML 文檔中的節點或者節點集。這些路徑表達式和我們在常規的電腦文件系統中看到的表達式非常相似。

1) 可在XML中查找信息
2) 支持HTML的查找
3) 通過元素和屬性進行導航

安裝

Windows
#pip安裝
pip3 install lxml
#wheel安裝
#下載對應系統版本的wheel文件:http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml
pip3 install lxml-4.2.1-cp36-cp36m-win_amd64.whl



Linux
yum install -y epel-release libxslt-devel libxml2-devel openssl-devel
pip3 install lxml

術語

節點(Node)

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

XPath的使用方法

nodename	     選取此節點的所有子節點
/	             從當前節點選取直接子節點
//	             從當前節點選取子孫節點
.  		         用來選取當前節點 
..               選取當前節點的父節點
@      選取屬性
*    通配符,選擇所有元素節點與元素名
@*	  選取所有屬性
[@attrib]	選取具有給定屬性的所有元素
[@attrib='value']	選取給定屬性具有給定值的所有元素
[tag]	選取所有具有指定元素的直接子節點
[tag='text']	選取所有具有指定元素並且文本內容是text節點

 /text()    獲取當前路徑下的文本內容 
 /@xxxx     提取當前路徑下標簽的屬性值 
 | 可選符    使用|可選取若干個路徑 如//p | //div 即在當前路徑下選取所有符合條件的p標簽和div標簽。 



另外還有starts-with(@屬性名稱,屬性字符相同部分),string(.)兩種重要的特殊方法

使用

讀取文本解析節點

from lxml import etree

text='''
<div>
    <ul>
         <li class="item-0"><a href="link1.html">第一個</a></li>
         <li class="item-1"><a href="link2.html">second item</a></li>
         <li class="item-0"><a href="link5.html">a屬性</a>
     </ul>
 </div>
'''
html=etree.HTML(text) #初始化生成一個XPath解析對象
result=etree.tostring(html,encoding='utf-8')   #解析對象輸出代碼
print(type(html))
print(type(result))
print(result.decode('utf-8'))

#etree會修復HTML文本節點
<class 'lxml.etree._Element'>
<class 'bytes'>
<html><body><div>
    <ul>
         <li class="item-0"><a href="link1.html">第一個</a></li>
         <li class="item-1"><a href="link2.html">second item</a></li>
         <li class="item-0"><a href="link5.html">a屬性</a>
     </li></ul>
 </div>
</body></html>

讀取HTML文件進行解析

from lxml import etree

html=etree.parse('test.html',etree.HTMLParser()) #指定解析器HTMLParser會根據文件修復HTML文件中缺失的如聲明信息
result=etree.tostring(html)   #解析成字節
#result=etree.tostringlist(html) #解析成列表
print(type(html))
print(type(result))
print(result)

#
<class 'lxml.etree._ElementTree'>
<class 'bytes'>
b'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">\n<html><body><div>&#13;\n    <ul>&#13;\n         <li class="item-0"><a href="link1.html">first item</a></li>&#13;\n         <li class="item-1"><a href="link2.html">second item</a></li>&#13;\n         <li class="item-inactive"><a href="link3.html">third item</a></li>&#13;\n         <li class="item-1"><a href="link4.html">fourth item</a></li>&#13;\n         <li class="item-0"><a href="link5.html">fifth item</a>&#13;\n     </li></ul>&#13;\n </div>&#13;\n</body></html>'

獲取節點

html=etree.parse('test',etree.HTMLParser())
result=html.xpath('//*')  #//代表獲取子孫節點,*代表獲取所有
html.xpath('//li')   #獲取所有子孫節點的li節點
result=html.xpath('//li/a')  #通過追加/a選擇所有li節點的所有直接a節點,因為//li用於選中所有li節點,/a用於選中li節點的所有直接子節點a

##獲取父節點
查找父節點可以使用..來實現也可以使用parent::來獲取父節點
 text='''
<div>
    <ul>
         <li class="item-0"><a href="link1.html">第一個</a></li>
         <li class="item-1"><a href="link2.html">second item</a></li>
     </ul>
 </div>
'''

html=etree.HTML(text,etree.HTMLParser())
result=html.xpath('//a[@href="link2.html"]/../@class')
result1=html.xpath('//a[@href="link2.html"]/parent::*/@class')


        

屬性匹配

#用@符號進行屬性過濾

from lxml import etree
from lxml.etree import HTMLParser
text='''
<div>
    <ul>
         <li class="item-0"><a href="link1.html">第一個</a></li>
         <li class="item-1"><a href="link2.html">second item</a></li>
     </ul>
 </div>
'''

html=etree.HTML(text,etree.HTMLParser())
result=html.xpath('//li[@class="item-1"]')
print(result)

獲取節點后的結果為列表
print(etree.tostring(result[0]))
b'<li class="item-1"><a href="link2.html">second item</a></li>\n     '

print(etree.tostring(result[0]).decode('utf-8'))
<li class="item-1"><a href="link2.html">second item</a></li>

獲取文本

from lxml import etree

text='''
<div>
    <ul>
         <li class="item-0"><a href="link1.html">第一個</a></li>
         <li class="item-1"><a href="link2.html">second item</a></li>
     </ul>
 </div>
'''

html=etree.HTML(text,etree.HTMLParser())
result=html.xpath('//li[@class="item-1"]/a/text()') #獲取a節點下的內容
result1=html.xpath('//li[@class="item-1"]//text()') #獲取li下所有子孫節點的內容

print(result)
print(result1)

獲取屬性

使用@符號即可獲取節點的屬性,如下:獲取所有li節點下所有a節點的href屬性
result=html.xpath('//li/a/@href')  #獲取a的href屬性
result=html.xpath('//li//@href')   #獲取所有li子孫節點的href屬性


多屬性值匹配

如果某個屬性的值有多個時,我們可以使用contains()函數來獲取
from lxml import etree

text1='''
<div>
    <ul>
         <li class="aaa item-0"><a href="link1.html">第一個</a></li>
         <li class="bbb item-1"><a href="link2.html">second item</a></li>
     </ul>
 </div>
'''

html=etree.HTML(text1,etree.HTMLParser())
result=html.xpath('//li[@class="aaa"]/a/text()')
result1=html.xpath('//li[contains(@class,"aaa")]/a/text()')

print(result)
print(result1)

#通過第一種方法沒有取到值,通過contains()就能精確匹配到節點了
[]
['第一個']

多屬性匹配

根據多個屬性確定一個節點,這時就需要同時匹配多個屬性,此時可用運用and運算符來連接使用

from lxml import etree

text1='''
<div>
    <ul>
         <li class="aaa" name="item"><a href="link1.html">第一個</a></li>
         <li class="aaa" name="fore"><a href="link2.html">second item</a></li>
     </ul>
 </div>
'''

html=etree.HTML(text1,etree.HTMLParser())
result=html.xpath('//li[@class="aaa" and @name="fore"]/a/text()')
result1=html.xpath('//li[contains(@class,"aaa") and @name="fore"]/a/text()')


print(result)
print(result1)


#
['second item']
['second item']

XPath中的運算符

運算符 描述 實例 返回值
or age=19 or age=20 如果age等於19或者等於20則返回true反正返回false
and age>19 and age<21 如果age等於20則返回true,否則返回false
mod 取余 5 mod 2 1
| 取兩個節點的集合 //book | //cd 返回所有擁有book和cd元素的節點集合
+ 6+4 10
- 6-4 2
* 6*4 24
div 除法 8 div 4 2
= 等於 age=19 true
!= 不等於 age!=19 true
< 小於 age<19 true
<= 小於或等於 age<=19 true
> 大於 age>19 true
>= 大於或等於 age>=19 true

按序選擇

我們在選擇的時候某些屬性可能同時匹配多個節點,但我們只想要其中的某個節點,如第二個節點或者最后一個節點,這時可以利用中括號引入索引的方法獲取特定次序的節點

from lxml import etree

text1='''
<div>
    <ul>
         <li class="aaa" name="item"><a href="link1.html">第一個</a></li>
         <li class="aaa" name="item"><a href="link1.html">第二個</a></li>
         <li class="aaa" name="item"><a href="link1.html">第三個</a></li>
         <li class="aaa" name="item"><a href="link1.html">第四個</a></li> 
     </ul>
 </div>
'''

html=etree.HTML(text1,etree.HTMLParser())

result=html.xpath('//li[contains(@class,"aaa")]/a/text()') #獲取所有li節點下a節點的內容
result1=html.xpath('//li[1][contains(@class,"aaa")]/a/text()') #獲取第一個
result2=html.xpath('//li[last()][contains(@class,"aaa")]/a/text()') #獲取最后一個
result3=html.xpath('//li[position()>2 and position()<4][contains(@class,"aaa")]/a/text()') #獲取第一個
result4=html.xpath('//li[last()-2][contains(@class,"aaa")]/a/text()') #獲取倒數第三個


print(result)
print(result1)
print(result2)
print(result3)
print(result4)


#
['第一個', '第二個', '第三個', '第四個']
['第一個']
['第四個']
['第三個']
['第二個']

last()、position()函數,在XPath中,提供了100多個函數,包括存取、數值、字符串、邏輯、節點、序列等處理功

節點軸選擇

獲取子元素、兄弟元素、父元素、祖先元素等

from lxml import etree

text1='''
<div>
    <ul>
         <li class="aaa" name="item"><a href="link1.html">第一個</a></li>
         <li class="aaa" name="item"><a href="link1.html">第二個</a></li>
         <li class="aaa" name="item"><a href="link1.html">第三個</a></li>
         <li class="aaa" name="item"><a href="link1.html">第四個</a></li> 
     </ul>
 </div>
'''

html=etree.HTML(text1,etree.HTMLParser())
result=html.xpath('//li[1]/ancestor::*')  #獲取所有祖先節點
result1=html.xpath('//li[1]/ancestor::div')  #獲取div祖先節點
result2=html.xpath('//li[1]/attribute::*')  #獲取所有屬性值
result3=html.xpath('//li[1]/child::*')  #獲取所有直接子節點
result4=html.xpath('//li[1]/descendant::a')  #獲取所有子孫節點的a節點
result5=html.xpath('//li[1]/following::*')  #獲取當前子節之后的所有節點
result6=html.xpath('//li[1]/following-sibling::*')  #獲取當前節點的所有同級節點


#
[<Element html at 0x3ca6b960c8>, <Element body at 0x3ca6b96088>, <Element div at 0x3ca6b96188>, <Element ul at 0x3ca6b961c8>]
[<Element div at 0x3ca6b96188>]
['aaa', 'item']
[<Element a at 0x3ca6b96248>]
[<Element a at 0x3ca6b96248>]
[<Element li at 0x3ca6b96308>, <Element a at 0x3ca6b96348>, <Element li at 0x3ca6b96388>, <Element a at 0x3ca6b963c8>, <Element li at 0x3ca6b96408>, <Element a at 0x3ca6b96488>]
[<Element li at 0x3ca6b96308>, <Element li at 0x3ca6b96388>, <Element li at 0x3ca6b96408>]

XPath的特殊用法

starts-with 解決標簽屬性值以相同字符串開頭的情況

from lxml import etree
html="""
    <body>
        <div id="aa">aa</div>
        <div id="ab">ab</div>
        <div id="ac">ac</div>
    </body>
    """
selector=etree.HTML(html)
content=selector.xpath('//div[starts-with(@id,"a")]/text()') #這里使用starts-with方法提取div的id標簽屬性值開頭為a的div標簽
for each in content:
    print each
#輸出結果為:
aa
ab
ac

string(.) 標簽套標簽

獲取一個標簽,然后獲取標簽內的所有文本

html="""
    <div id="a">
    left
        <span id="b">
        right
            <ul>
            up
                <li>down</li>
            </ul>
        east
        </span>
        west
    </div>
"""
#下面是沒有用string方法的輸出
sel=etree.HTML(html)
con=sel.xpath('//div[@id="a"]/text()')
for i in con:
    print(i)  #輸出內容為left west
#輸出,會有換行

    left
        

        west
    


data=sel.xpath('//div[@id="a"]')[0]
info=data.xpath('string(.)') ##會將當前獲取的element內的所有字符串提取出來,並保留空格和換行
content=info.replace('\n','').replace(' ','')##將換行和空格刪除
print(info)
print(content)
for i in content:
     print(i) #輸出為 全部內容


XPath中需要取的標簽如果沒有屬性,可以使用text(),posision()來識別標簽

from lxml import etree
html="""
    <div>hello
        <p>H</p>
</div>
<div>hehe</div>
"""
sel=etree.HTML(html)
con=sel.xpath('//div[text()="hello"]/p/text()') #使用text()的方法來判別是哪個div標簽
print con[0]
#H

from lxml import etree
html="""
    <div>hello
        <p>H</p>
        <p>J</p>
        <p>I</p>
</div>
<div>hehe</div>
"""
sel=etree.HTML(html)
con=sel.xpath('//div[text()="hello"]/p[posision()=2]/text()')
print con[0]
#J


在XPath中可以使用多重過濾方法尋找標簽,例如ul[3][@id=”a”] 這里使用【3】來尋找第三個ul標簽 並且它的id屬性值為a

對結果繼續使用xpath

如果XPath語句用於查找節點, 那么返回的就是一個HtmlElement對象的列表,既然是HtmlElemtn對象,我們就還可以對其調用xpath()方法

注意:

在對xpath返回的對象再次執行xpath時,子xpath開頭不需要添加斜線,直接以標簽名開始即可

useful = selector.xpath('//div[@class="useful"]')
info_list = useful.xpath('ul/li/text()')

_Element對象和HtmlElement對象$

from lxml import etree

text = '''
<div>
    <ul>
         <li class="item-0"><a href="link1.html">first item</a></li>
         <li class="item-1"><a href="link2.html">second item</a></li>
         <li class="item-inactive"><a href="link3.html">third item</a></li>
         <li class="item-1"><a href="link4.html">fourth item</a></li>
         <li class="item-0"><a href="link5.html">fifth item</a>
     </ul>
 </div>
 '''
#(1)
html = etree.HTML(text)  
#調用HTML類進行初始化,構造一個節點對象,一個XPath解析對象,(順便也修正了HTML字符串)
#type(html):    <class 'lxml.etree._Element'>
#lxml 使用etree._Element和 etree._ElementTree來分別代表樹中的節點和樹


#(2)
html2 = etree.parse(r"C:\Users\byqpz\Desktop\html.html",etree.HTMLParser()) 
#讀取html文件進行解析
#構造一個節點樹對象,一個XPath解析對象
#type(html2):   <class 'lxml.etree._ElementTree'>

'''
result = etree.tostring(html)  #調用tostring()方法可以輸出修正后的HTML代碼,但結果是bytes類型                               
                               #type(result):<class 'bytes'>

print(result.decode('utf-8'))  #這里用decode()方法將其轉成str類型
                               #type(result.decode('utf-8')):<class 'str'>


#或 str()方法
print(str(result,encoding='utf-8'))

print(type(result))  #兩種方法都不會改變result

獲取XPath的方式有兩種(這個好):

1) 使用以上等等的方法通過觀察找規律的方式來獲取XPath
2) 使用Chrome瀏覽器來獲取 在網頁中右擊->選擇審查元素(或者使用F12打開) 就可以在elements中查看網頁的html標簽了,找到你想要獲取XPath的標簽,右擊->Copy XPath 就已經將XPath路徑復制到了剪切板。

案例

#!/usr/bin/env python
#coding:utf-8
import requests
from requests.exceptions import RequestException
from lxml import etree
from lxml.etree import ParseError
import json

def one_to_page(html):
    headers={
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36'
    }
    try:
        response=requests.get(html,headers=headers)
        body=response.text  #獲取網頁內容
    except RequestException as e:
        print('request is error!',e)
    try:
        html=etree.HTML(body,etree.HTMLParser())  #解析HTML文本內容
        result=html.xpath('//table[contains(@class,"table-top20")]/tbody/tr//text()') #獲取列表數據,獲取的text()會生成列表,每5個為一行
        pos = 0
        
        #####
        ###生成器:執行到yield時就會停下來,直到循環獲取該生成器才會逐個產生值
        ####
        for i in range(20):
            if i == 0:
                yield result[i:5]
            else:
                yield result[pos:pos+5]  #返回排名生成器數據
            pos+=5
    except ParseError as e:
         print(e.position)


def write_file(data):   #將數據重新組合成字典寫入文件並輸出
    for i in data:
        sul={
            '2018年6月排行':i[0],
            '2017年6排行':i[1],
            '開發語言':i[2],
            '評級':i[3],
            '變化率':i[4]
        }
        with open('test.txt','a',encoding='utf-8') as f:
            f.write(json.dumps(sul,ensure_ascii=False) + '\n') #必須格式化數據
            f.close()
        print(sul)
    return None


def main():
    url='https://www.tiobe.com/tiobe-index/'
    data=one_to_page(url)
    revaule=write_file(data)
    if revaule == None:
        print('ok')
        
 
 
        
if __name__ == '__main__':
    main()



#
{'2018年6月排行': '1', '2017年6排行': '1', '開發語言': 'Java', '評級': '15.368%', '變化率': '+0.88%'}
{'2018年6月排行': '2', '2017年6排行': '2', '開發語言': 'C', '評級': '14.936%', '變化率': '+8.09%'}
{'2018年6月排行': '3', '2017年6排行': '3', '開發語言': 'C++', '評級': '8.337%', '變化率': '+2.61%'}
{'2018年6月排行': '4', '2017年6排行': '4', '開發語言': 'Python', '評級': '5.761%', '變化率': '+1.43%'}
{'2018年6月排行': '5', '2017年6排行': '5', '開發語言': 'C#', '評級': '4.314%', '變化率': '+0.78%'}
{'2018年6月排行': '6', '2017年6排行': '6', '開發語言': 'Visual Basic .NET', '評級': '3.762%', '變化率': '+0.65%'}
{'2018年6月排行': '7', '2017年6排行': '8', '開發語言': 'PHP', '評級': '2.881%', '變化率': '+0.11%'}
{'2018年6月排行': '8', '2017年6排行': '7', '開發語言': 'JavaScript', '評級': '2.495%', '變化率': '-0.53%'}
{'2018年6月排行': '9', '2017年6排行': '-', '開發語言': 'SQL', '評級': '2.339%', '變化率': '+2.34%'}
{'2018年6月排行': '10', '2017年6排行': '14', '開發語言': 'R', '評級': '1.452%', '變化率': '-0.70%'}
{'2018年6月排行': '11', '2017年6排行': '11', '開發語言': 'Ruby', '評級': '1.253%', '變化率': '-0.97%'}
{'2018年6月排行': '12', '2017年6排行': '18', '開發語言': 'Objective-C', '評級': '1.181%', '變化率': '-0.78%'}
{'2018年6月排行': '13', '2017年6排行': '16', '開發語言': 'Visual Basic', '評級': '1.154%', '變化率': '-0.86%'}
{'2018年6月排行': '14', '2017年6排行': '9', '開發語言': 'Perl', '評級': '1.147%', '變化率': '-1.16%'}
{'2018年6月排行': '15', '2017年6排行': '12', '開發語言': 'Swift', '評級': '1.145%', '變化率': '-1.06%'}
{'2018年6月排行': '16', '2017年6排行': '10', '開發語言': 'Assembly language', '評級': '0.915%', '變化率': '-1.34%'}
{'2018年6月排行': '17', '2017年6排行': '17', '開發語言': 'MATLAB', '評級': '0.894%', '變化率': '-1.10%'}
{'2018年6月排行': '18', '2017年6排行': '15', '開發語言': 'Go', '評級': '0.879%', '變化率': '-1.17%'}
{'2018年6月排行': '19', '2017年6排行': '13', '開發語言': 'Delphi/Object Pascal', '評級': '0.875%', '變化率': '-1.28%'}
{'2018年6月排行': '20', '2017年6排行': '20', '開發語言': 'PL/SQL', '評級': '0.848%', '變化率': '-0.72%'}

參考

https://www.cnblogs.com/zhangxinqi/p/9210211.html

https://lxml.de/api/lxml.etree._Element-class.html

https://zhuanlan.zhihu.com/p/41969389


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM