xpath學(xué)習(xí)

什么是 XPath

XPath是一門在XML文檔中查找信息的語言. XPath用于在XML文檔中通過元素和屬性進(jìn)行導(dǎo)航.
XPath使用路徑表達(dá)式在XML文檔中進(jìn)行導(dǎo)航
XPath包含一個(gè)標(biāo)準(zhǔn)函數(shù)庫
XPath是XSLT中的主要元素
XPath是一個(gè)W3C 標(biāo)準(zhǔn)

XPath 術(shù)語

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

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>  // 文檔根節(jié)點(diǎn)
    <book>
      <title lang="en">   // 元素節(jié)點(diǎn)
        Harry Potter
      </title> 
      <author>J K. Rowling</author>  // 元素節(jié)點(diǎn)
      <year>2005</year>
      <price>29.99</price>
    </book>
</bookstore>

選取節(jié)點(diǎn)

下面列出了最有用的路徑表達(dá)式:

表達(dá)式       描述
nodename    選取此節(jié)點(diǎn)的所有子節(jié)點(diǎn)。
/           從根節(jié)點(diǎn)選取。
//          從匹配選擇的當(dāng)前節(jié)點(diǎn)選擇文檔中的節(jié)點(diǎn),而不考慮它們的位置。
.           選取當(dāng)前節(jié)點(diǎn)。
..          選取當(dāng)前節(jié)點(diǎn)的父節(jié)點(diǎn)。
@           選取屬性。

在下面的表格中,我們已列出了一些路徑表達(dá)式以及表達(dá)式的結(jié)果:

路徑表達(dá)式           結(jié)果
bookstore           選取 bookstore 元素的所有子節(jié)點(diǎn)
/bookstore          選取根元素 bookstore
bookstore/book      選取屬于bookstore 的子元素的所有 book 元素。
//book              選取所有book 子元素,而不管它們在文檔中的位置。
bookstore//book     選擇屬于bookstore 元素的后代的所有 book 元素,
                    而不管它們位于bookstore 之下的什么位置。
//@lang             選取名為 lang 的所有屬性。

謂語 (Predicates)

謂語用來查找某個(gè)特定的節(jié)點(diǎn)或者包含某個(gè)指定的值的節(jié)點(diǎn)(謂語被嵌在方括號(hào)中)

/bookstore/book[1]             選取屬于bookstore子元素的第一個(gè)book元素。
/bookstore/book[last()]        選取屬于bookstore子元素的最后一個(gè)book元素。
/bookstore/book[last()-1]      選取屬于bookstore子元素的倒數(shù)第二個(gè)book元素
/bookstore/book[position()<3]  選取最前面的兩個(gè)屬于bookstore元素的子元素的book元素
//title[@lang]                 選取所有擁有名為 lang 的屬性的 title 元素
//title[@lang='eng']           選取所有title元素,且這些元素?fù)碛兄禐閑ng的lang 屬性
/bookstore/book[price>35.00]   選取bookstore元素的所有book元素,
                               且其中的price元素的值須大于35.00
/bookstore/book[price>35.00]/title  選取bookstore元素中的book元素的所有title元素,
                                    且其中的 price 元素的值須大于 35.00

選取未知節(jié)點(diǎn)

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

通配符           描述
*               匹配任何元素節(jié)點(diǎn)
@*              匹配任何屬性節(jié)點(diǎn)
node()          匹配任何類型的節(jié)點(diǎn)

在下面的表格中,我們列出了一些路徑表達(dá)式,以及這些表達(dá)式的結(jié)果

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

選取若干路徑

通過在路徑表達(dá)式中使用"|"運(yùn)算符,您可以選取若干個(gè)路徑
在下面的表格中,我們列出了一些路徑表達(dá)式,以及這些表達(dá)式的結(jié)果:

路徑表達(dá)式                       結(jié)果
//book/title | //book/price     選取book元素的所有title和price元素
//title | //price               選取文檔中的所有title和price元素
/bookstore/book/title | //price 選取屬于bookstore元素的book元素的所有title元素
                                以及文檔中所有的price元素

lxml實(shí)例學(xué)習(xí)

安裝lxml pip install lxml

1、本地文件&硬編碼

from lxml import etree

''' for file approach
xml = etree.parse('books.xml');
text = xml.xpath('/bookstore/book/title/text()')
'''
content = '''
<bookstore>
    <book category="COOKING">
      <title lang="en">Everyday Italian</title>
      <author>Giada De Laurentiis</author>
      <year>2005</year>
      <price>30.00</price>
    </book>
    <book category="CHILDREN">
      <title lang="en">Harry Potter</title>
      <author>J K. Rowling</author>
      <year>2005</year>
      <price>29.99</price>
    </book>
    <book category="WEB">
      <title lang="en">XQuery Kick Start</title>
      <author>James McGovern</author>
      <author>Per Bothner</author>
      <author>Kurt Cagle</author>
      <author>James Linn</author>
      <author>Vaidyanathan Nagarajan</author>
      <year>2003</year>
      <price>49.99</price>
    </book>
    <book category="WEB">
      <title lang="en">Learning XML</title>
      <author>Erik T. Ray</author>
      <year>2003</year>
      <price>39.95</price>
    </book>
</bookstore>
''';

#content_1 = etree.tostring(content, pretty_print=True)
xml = etree.XML(content)
print(xml.xpath('/bookstore/book/title/text()'))

2、抓取網(wǎng)頁xml文件

from lxml import etree
from urllib.request import Request, urlopen
from urllib.parse import urlencode
from urllib.error import HTTPError
from html.parser import HTMLParser
import chardet
import io
import gzip

url_heads = {
    'Accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Connection': 'keep-alive',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Host': 'www.itdecent.cn',
    'Origin': 'http://www.itdecent.cn',
    'Referer': 'http://www.itdecent.cn/p/569c1c0afe1f',
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
    'X-Requested-With':'XMLHttpRequest'
}

url_data = {
    'username': 'elan',
    'password': '1234'
};

try:
    # handle escape character
    html_parser = HTMLParser();
    # encode post data
    encode_data = urlencode(url_data);
    # url address
    url = 'http://www.itdecent.cn/p/569c1c0afe1f';
    # prepare request template
    req = Request(url=url, headers=url_heads);
    # fetch raw data
    content_raw = urlopen(req).read();
    # fetch the encoding
    encoding = chardet.detect(content_raw);
    print('encoding:', encoding);
    # gzip
    content_unzip = gzip.GzipFile(fileobj=io.BytesIO(content_raw), mode="rb").read()
    # decode to utf-8
    if encoding not in ( 'utf-8', 'UTF-8' ) :
       content = content_unzip.decode('utf-8', 'ignore')
    else:
       content = content_unzip.read()
    content = html_parser.unescape(content)
    xml = etree.HTML(content)
    # 抓取所有標(biāo)題
    output = xml.xpath('/html//h2/text() | /html//h1/text()');
    print(output)
except HTTPError as e:
    print(e.code)

感謝

w3school xpath教程

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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