日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python爬虫之xlml解析库

發(fā)布時間:2024/3/13 python 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python爬虫之xlml解析库 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1.Xpath

  Xpath是一門在XML中查找信息的語言,可用來在XML文檔中對元素和屬性進行遍歷。XQuery和xpoint都是構(gòu)建于xpath表達之上

2.節(jié)點

  父(parent),子(children),兄弟(sibling),先輩(ancetstor),后代(Decendant)

3.選取節(jié)點

路徑表達式

表達式描述路徑表達式結(jié)果
nodename選取此節(jié)點上的所有的子節(jié)點bookstore選取bookstore元素的所有子節(jié)點
/從根節(jié)點上選取/bookstore選取根元素bookstore,為絕對路徑
//從匹配選擇的當前節(jié)點選擇文檔中的節(jié)點,不考慮位置//book選取所有的book子元素,而不管他們在文檔的位置
.選取當前節(jié)點bookstore//book選擇bookstore后代中所有的book元素
..選取當前節(jié)點的父節(jié)點??
@選取屬性//@lang選取名為lang的所有屬性

?

?

?

?

?

?

?

?

謂語

  謂語用來查找某個特定的節(jié)點或者包含某個指定的值的節(jié)點

  謂語被嵌在方括號中

路徑表達式結(jié)果
/bookstore/book[1]選取屬于bookstore子元素的第一個book元素
/bookstore/book[last()]選取屬于bookstore子元素的最后book元素
/bookstore/book[last()-1]選取屬于bookstore子元素的倒數(shù)第二個book元素
/bookstore/book[position()<3]選取最前面的兩個屬于bookstore元素的子元素的book元素
//title[@lang='eng']選取所有的title元素,并且這些元素擁有值為eng的lang屬性
/bookstore/book[price>35.0]選取bookstore元素的所有book元素,且其中的price值大于35.0

?

?

?

?

?

?

?

?

?

?

選取未知節(jié)點(通配符)

*  匹配任何 元素節(jié)點

@*  匹配任何屬性節(jié)點

node()  匹配任何類型的節(jié)點

?

4.lxml用法

#!/usr/bin/python #_*_coding:utf-8_*_from lxml import etreetext=''' <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>'''# html=etree.HTML(text) #html對象,存儲在地址中,有自動修正功能 # result=etree.tostring(html) #將html對象轉(zhuǎn)化為字符串 html=etree.parse('hello.html') # result=etree.tostring(html,pretty_print=True) # print result print type(html) result= html.xpath('//li') print result print len(result) print type(result) print type(result[0]) print html.xpath('//li/@class') # 獲取li標簽下的所有的class print html.xpath('//li/a[@href="link1.html"]') #獲取li標簽下href為link1的<a>標簽 print html.xpath('//li//span') #獲取li標簽下所有的span標簽 print html.xpath('//li[last()-1]/a')[0].text #獲取倒數(shù)第二個元素的內(nèi)容

?

轉(zhuǎn)載于:https://www.cnblogs.com/sjtu-ly-2017/p/7301215.html

總結(jié)

以上是生活随笔為你收集整理的Python爬虫之xlml解析库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。