国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python爬蟲之xpath的基本使用詳解

2020-02-22 23:42:48
字體:
來源:轉載
供稿:網友

一、簡介

XPath 是一門在 XML 文檔中查找信息的語言。XPath 可用來在 XML 文檔中對元素和屬性進行遍歷。XPath 是 W3C XSLT 標準的主要元素,并且 XQuery 和 XPointer 都構建于 XPath 表達之上。 

二、安裝

pip3 install lxml 

三、使用

1、導入

from lxml import etree 

2、基本使用

from lxml import etreewb_data = """    <div>      <ul>         <li class="item-0"><a href="link1.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >first item</a></li>         <li class="item-1"><a href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >second item</a></li>         <li class="item-inactive"><a href="link3.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >third item</a></li>         <li class="item-1"><a href="link4.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fourth item</a></li>         <li class="item-0"><a href="link5.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fifth item</a>       </ul>     </div>    """html = etree.HTML(wb_data)print(html)result = etree.tostring(html)print(result.decode("utf-8")) 

從下面的結果來看,我們打印機html其實就是一個python對象,etree.tostring(html)則是不全里html的基本寫法,補全了缺胳膊少腿的標簽。

 <Element html at 0x39e58f0><html><body><div>      <ul>         <li class="item-0"><a href="link1.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >first item</a></li>         <li class="item-1"><a href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >second item</a></li>         <li class="item-inactive"><a href="link3.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >third item</a></li>         <li class="item-1"><a href="link4.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fourth item</a></li>         <li class="item-0"><a href="link5.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" >fifth item</a>       </li></ul>     </div>    </body></html> 

3、獲取某個標簽的內容(基本使用),注意,獲取a標簽的所有內容,a后面就不用再加正斜杠,否則報錯。

寫法一

html = etree.HTML(wb_data)html_data = html.xpath('/html/body/div/ul/li/a')print(html)for i in html_data:  print(i.text)<Element html at 0x12fe4b8>first itemsecond itemthird itemfourth itemfifth item             
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 额尔古纳市| 逊克县| 财经| 油尖旺区| 罗定市| 姜堰市| 营山县| 木兰县| 漳州市| 同仁县| 息烽县| 麻栗坡县| 措勤县| 高雄县| 霍山县| 清河县| 太仆寺旗| 南昌市| 中西区| 洛扎县| 德兴市| 越西县| 通州市| 桂林市| 舞钢市| 新乡县| 建阳市| 金溪县| 密山市| 天台县| 扎赉特旗| 桓仁| 保山市| 伊宁县| 武陟县| 楚雄市| 峨眉山市| 临汾市| 房产| 房产| 嘉禾县|