搜尋
首頁後端開發Python教學python爬蟲之xpath的基本使用詳解

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

Apr 27, 2018 am 11:01 AM
pythonxpath使用

這篇文章主要介紹了python爬蟲之xpath的基本使用詳解,現在分享給大家,也給大家做個參考。一起來看看吧

一、簡介

#XPath 是一種在 XML 文件中尋找資訊的語言。 XPath 可用於在 XML 文件中對元素和屬性進行遍歷。 XPath 是 W3C XSLT 標準的主要元素,而 XQuery 和 XPointer 都建構在 XPath 表達之上。

二、安裝

#
pip3 install lxml

三、使用

1、導入

from lxml import etree

2、基本使用

from lxml import etree
wb_data = """
    <p>
      <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>
     </p>

    """
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><p>
      <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>
     </p>
    </body></html>

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

寫法一

html = etree.HTML(wb_data)

html_data = html.xpath(&#39;/html/body/p/ul/li/a&#39;)

print(html)

for i in html_data:

  print(i.text)

<Element html at 0x12fe4b8>

first item

second item

third item

fourth item

fifth item

#寫法二(直接在需要尋找內容的標籤後面加上一個/text()就行)

html = etree.HTML(wb_data)

html_data = html.xpath(&#39;/html/body/p/ul/li/a/text()&#39;)

print(html)

for i in html_data:

  print(i) 

<Element html at 0x138e4b8>

first item

second item

third item

fourth item

fifth item

4、開啟讀取html檔案

#
#使用parse打开html的文件

html = etree.parse(&#39;test.html&#39;)

html_data = html.xpath(&#39;//*&#39;)<br>#打印是一个列表,需要遍历

print(html_data)

for i in html_data:

  print(i.text)

html = etree.parse(&#39;test.html&#39;)

html_data = etree.tostring(html,pretty_print=True)

res = html_data.decode(&#39;utf-8&#39;)

print(res)

 

打印:

<p>

   <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>

</p>

5、列印指定路徑下a標籤的屬性(可以透過遍歷拿到某個屬性的值,找出標籤的內容)

html = etree.HTML(wb_data)

html_data = html.xpath(&#39;/html/body/p/ul/li/a/@href&#39;)

for i in html_data:

  print(i)

列印:

link1.html

link2.html

link3.html

link4.html

link5.html

6、我們知道我們使用xpath拿到得都是一個個的ElementTree對象,所以如果需要找內容的話,還需要遍歷拿到資料的列表。

查到絕對路徑下a標籤屬性等於link2.html的內容。

html = etree.HTML(wb_data)

html_data = html.xpath(&#39;/html/body/p/ul/li/a[@href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ]/text()&#39;)

print(html_data)

for i in html_data:

  print(i)

列印:

#['second item']

second item

#7、上面我們找到全部都是絕對路徑(每一個都是從根開始查找),下面我們查找相對路徑,例如,查找所有li標籤下的a標籤內容。

html = etree.HTML(wb_data)

html_data = html.xpath(&#39;//li/a/text()&#39;)

print(html_data)

for i in html_data:

  print(i)

印刷:

['first item', 'second item', 'third item', 'fourth item' , 'fifth item']

first item

second item

third item

fourth item

fifth item

8、上面我們使用絕對路徑,查找了所有a標籤的屬性等於href屬性值,利用的是/---絕對路徑,下面我們使用相對路徑,查找l相對路徑下li標籤下的a標籤下的href屬性的值,注意,a標籤後面需要雙//。

html = etree.HTML(wb_data)

html_data = html.xpath(&#39;//li/a//@href&#39;)

print(html_data)

for i in html_data:

  print(i)

列印:

#['link1.html', 'link2.html', 'link3.html', ' link4.html', 'link5.html']

link1.html

link2.html

link3.html

link4.html

#link5.html

9、相對路徑下跟絕對路徑下查特定屬性的方法類似,也可以說相同。

html = etree.HTML(wb_data)

html_data = html.xpath(&#39;//li/a[@href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ]&#39;)

print(html_data)

for i in html_data:

  print(i.text)

列印:

[]

#second item

10、找出最後一個li標籤裡的a標籤的href屬性

#
html = etree.HTML(wb_data)

html_data = html.xpath(&#39;//li[last()]/a/text()&#39;)

print(html_data)

for i in html_data:

  print(i)

列印:

['fifth item']

fifth item

11、找出倒數第二個li標籤裡的a標籤的href屬性 

#
html = etree.HTML(wb_data)

html_data = html.xpath(&#39;//li[last()-1]/a/text()&#39;)

print(html_data)

for i in html_data:

  print(i)

列印:

['fourth item']

fourth item

12、如果在擷取某個頁面的某個標籤的xpath路徑的話,可以如下圖:

//*[@id="kw"]

解釋:使用相對路徑來尋找所有的標籤,屬性id等於kw的標籤。

常用

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from scrapy.selector import Selector, HtmlXPathSelector
from scrapy.http import HtmlResponse
html = """<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    <ul>
      <li class="item-"><a id=&#39;i1&#39; href="link.html" rel="external nofollow" rel="external nofollow" >first item</a></li>
      <li class="item-0"><a id=&#39;i2&#39; href="llink.html" rel="external nofollow" >first item</a></li>
      <li class="item-1"><a href="llink2.html" rel="external nofollow" rel="external nofollow" >second item<span>vv</span></a></li>
    </ul>
    <p><a href="llink2.html" rel="external nofollow" rel="external nofollow" >second item</a></p>
  </body>
</html>
"""
response = HtmlResponse(url=&#39;http://example.com&#39;, body=html,encoding=&#39;utf-8&#39;)
# hxs = HtmlXPathSelector(response)
# print(hxs)
# hxs = Selector(response=response).xpath(&#39;//a&#39;)
# print(hxs)
# hxs = Selector(response=response).xpath(&#39;//a[2]&#39;)
# print(hxs)
# hxs = Selector(response=response).xpath(&#39;//a[@id]&#39;)
# print(hxs)
# hxs = Selector(response=response).xpath(&#39;//a[@id="i1"]&#39;)
# print(hxs)
# hxs = Selector(response=response).xpath(&#39;//a[@href="link.html" rel="external nofollow" rel="external nofollow" ][@id="i1"]&#39;)
# print(hxs)
# hxs = Selector(response=response).xpath(&#39;//a[contains(@href, "link")]&#39;)
# print(hxs)
# hxs = Selector(response=response).xpath(&#39;//a[starts-with(@href, "link")]&#39;)
# print(hxs)
# hxs = Selector(response=response).xpath(&#39;//a[re:test(@id, "i\d+")]&#39;)
# print(hxs)
# hxs = Selector(response=response).xpath(&#39;//a[re:test(@id, "i\d+")]/text()&#39;).extract()
# print(hxs)
# hxs = Selector(response=response).xpath(&#39;//a[re:test(@id, "i\d+")]/@href&#39;).extract()
# print(hxs)
# hxs = Selector(response=response).xpath(&#39;/html/body/ul/li/a/@href&#39;).extract()
# print(hxs)
# hxs = Selector(response=response).xpath(&#39;//body/ul/li/a/@href&#39;).extract_first()
# print(hxs)
 
# ul_list = Selector(response=response).xpath(&#39;//body/ul/li&#39;)
# for item in ul_list:
#   v = item.xpath(&#39;./a/span&#39;)
#   # 或
#   # v = item.xpath(&#39;a/span&#39;)
#   # 或
#   # v = item.xpath(&#39;*/a/span&#39;)
#   print(v)

相關推薦:

#python爬蟲使用真實瀏覽器開啟網頁的兩種方法總結


以上是python爬蟲之xpath的基本使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python中如何實現工廠模式?Python中如何實現工廠模式?May 16, 2025 pm 12:39 PM

在Python中實現工廠模式可以通過創建一個統一的接口來創建不同類型的對象。具體步驟如下:1.定義一個基礎類和多個繼承類,如Vehicle、Car、Plane和Train。 2.創建一個工廠類VehicleFactory,使用create_vehicle方法根據類型參數返回相應的對象實例。 3.通過工廠類實例化對象,如my_car=factory.create_vehicle("car","Tesla")。這種模式提高了代碼的可擴展性和可維護性,但需注意其複雜

python中r是什麼意思 python原始字符串前綴python中r是什麼意思 python原始字符串前綴May 16, 2025 pm 12:36 PM

在Python中,r或R前綴用於定義原始字符串,忽略所有轉義字符,讓字符串按字面意思解釋。 1)適用於處理正則表達式和文件路徑,避免轉義字符誤解。 2)不適用於需要保留轉義字符的情況,如換行符。使用時需謹慎檢查,以防意外的輸出。

Python中如何使用__del__方法清理資源?Python中如何使用__del__方法清理資源?May 16, 2025 pm 12:33 PM

在Python中,__del__方法是對象的析構函數,用於清理資源。 1)不確定的執行時間:依賴垃圾回收機制。 2)循環引用:可能導致無法及時調用,使用weakref模塊處理。 3)異常處理:在__del__中拋出的異常可能被忽略,使用try-except塊捕獲。 4)資源管理的最佳實踐:推薦使用with語句和上下文管理器管理資源。

python中pop()函數的用法 python列表pop元素移除方法詳解python中pop()函數的用法 python列表pop元素移除方法詳解May 16, 2025 pm 12:30 PM

pop()函數在Python中用於從列表中移除並返回指定位置的元素。 1)不指定索引時,pop()默認移除並返回列表的最後一個元素。 2)指定索引時,pop()移除並返回該索引位置的元素。 3)使用時需注意索引錯誤、性能問題、替代方法和列表的可變性。

如何用Python進行圖像處理?如何用Python進行圖像處理?May 16, 2025 pm 12:27 PM

Python進行圖像處理主要使用Pillow和OpenCV兩大庫。 Pillow適合簡單圖像處理,如加水印,代碼簡潔易用;OpenCV適用於復雜圖像處理和計算機視覺,如邊緣檢測,性能優越但需注意內存管理。

Python中怎樣實現主成分分析?Python中怎樣實現主成分分析?May 16, 2025 pm 12:24 PM

在Python中實現PCA可以通過手動編寫代碼或使用scikit-learn庫。手動實現PCA包括以下步驟:1)中心化數據,2)計算協方差矩陣,3)計算特徵值和特徵向量,4)排序並選擇主成分,5)投影數據到新空間。手動實現有助於深入理解算法,但scikit-learn提供更便捷的功能。

怎樣用Python計算對數?怎樣用Python計算對數?May 16, 2025 pm 12:21 PM

在Python中計算對數是一件非常簡單卻又充滿趣味的事情。讓我們從最基本的問題開始:怎樣用Python計算對數?用Python計算對數的基本方法Python的math模塊提供了計算對數的函數。讓我們來看一個簡單的例子:importmath#計算自然對數(底數為e)x=10natural_log=math.log(x)print(f"自然對數log({x})={natural_log}")#計算以10為底的對數log_base_10=math.log10(x)pri

Python中如何實現線性回歸?Python中如何實現線性回歸?May 16, 2025 pm 12:18 PM

要在Python中實現線性回歸,我們可以從多個角度出發。這不僅僅是一個簡單的函數調用,而是涉及到統計學、數學優化和機器學習的綜合應用。讓我們深入探討一下這個過程。在Python中實現線性回歸最常見的方法是使用scikit-learn庫,它提供了簡便且高效的工具。然而,如果我們想要更深入地理解線性回歸的原理和實現細節,我們也可以從頭開始編寫自己的線性回歸算法。使用scikit-learn實現線性回歸scikit-learn庫封裝了線性回歸的實現,使得我們可以輕鬆地進行建模和預測。下面是一個使用sc

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。