python的xpath用法介紹_python爬蟲之xpath的基本使用詳解

本篇文章主要介紹了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 = """

  • first item
  • second item
  • third item
  • fourth item
  • fifth item

"""

html = etree.HTML(wb_data)

print(html)

result = etree.tostring(html)

print(result.decode("utf-8"))

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

  • first item
  • second item
  • third item
  • fourth item
  • fifth item

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

寫法一

html = etree.HTML(wb_data)

html_data = html.xpath('/html/body/p/ul/li/a')

print(html)

for i in html_data:

print(i.text)

first item

second item

third item

fourth item

fifth item

寫法二(直接在需要查找內容的標簽后面加一個/text()就行)

html = etree.HTML(wb_data)

html_data = html.xpath('/html/body/p/ul/li/a/text()')

print(html)

for i in html_data:

print(i)

first item

second item

third item

fourth item

fifth item

4、打開讀取html文件

#使用parse打開html的文件

html = etree.parse('test.html')

html_data = html.xpath('//*')
#打印是一個列表,需要遍歷

print(html_data)

for i in html_data:

print(i.text)

html = etree.parse('test.html')

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

res = html_data.decode('utf-8')

print(res)

打印:

  • first item
  • second item
  • third item
  • fourth item
  • fifth item

5、打印指定路徑下a標簽的屬性(可以通過遍歷拿到某個屬性的值,查找標簽的內容)

html = etree.HTML(wb_data)

html_data = html.xpath('/html/body/p/ul/li/a/@href')

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('/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()')

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('//li/a/text()')

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('//li/a//@href')

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('//li/a[@href="link2.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ]')

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('//li[last()]/a/text()')

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('//li[last()-1]/a/text()')

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

  • first item
  • first item
  • second itemvv

second item

"""

response = HtmlResponse(url='http://example.com', body=html,encoding='utf-8')

# hxs = HtmlXPathSelector(response)

# print(hxs)

# hxs = Selector(response=response).xpath('//a')

# print(hxs)

# hxs = Selector(response=response).xpath('//a[2]')

# print(hxs)

# hxs = Selector(response=response).xpath('//a[@id]')

# print(hxs)

# hxs = Selector(response=response).xpath('//a[@id="i1"]')

# print(hxs)

# hxs = Selector(response=response).xpath('//a[@href="link.html" rel="external nofollow" rel="external nofollow" ][@id="i1"]')

# print(hxs)

# hxs = Selector(response=response).xpath('//a[contains(@href, "link")]')

# print(hxs)

# hxs = Selector(response=response).xpath('//a[starts-with(@href, "link")]')

# print(hxs)

# hxs = Selector(response=response).xpath('//a[re:test(@id, "i\d+")]')

# print(hxs)

# hxs = Selector(response=response).xpath('//a[re:test(@id, "i\d+")]/text()').extract()

# print(hxs)

# hxs = Selector(response=response).xpath('//a[re:test(@id, "i\d+")]/@href').extract()

# print(hxs)

# hxs = Selector(response=response).xpath('/html/body/ul/li/a/@href').extract()

# print(hxs)

# hxs = Selector(response=response).xpath('//body/ul/li/a/@href').extract_first()

# print(hxs)

# ul_list = Selector(response=response).xpath('//body/ul/li')

# for item in ul_list:

# v = item.xpath('./a/span')

# # 或

# # v = item.xpath('a/span')

# # 或

# # v = item.xpath('*/a/span')

# print(v)

相關推薦:

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394308.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394308.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394308.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

楊波 微服務技術專家_專家稱,這些是最有效的微服務測試策略

楊波 微服務技術專家by Jake Lumetta杰克盧米塔(Jake Lumetta) 專家稱,這些是最有效的微服務測試策略 (These are the most effective microservice testing strategies, according to the experts) Testing microservices is hard. More specifically, end-to-end…

LRU算法實現

LRU是Last Recent Used 縮寫,做為一種緩存算法,將最近較少使用的緩存失效。memcache采用了該算法。如下采用了一種PHP的實現方式。該算法將每次新增的內容,放到緩存頂部,達到緩存極限時,將緩存底部的內容清除。可以通過…

Java中的阻塞隊列-LinkedBlockingQueue(二)

原文地址:http://benjaminwhx.com/2018/05/11/%E3%80%90%E7%BB%86%E8%B0%88Java%E5%B9%B6%E5%8F%91%E3%80%91%E8%B0%88%E8%B0%88LinkedBlockingQueue/ 在集合框架里,想必大家都用過ArrayList和LinkedList,也經常在面試中問到他們之間的區別。…

自動加密企業關鍵業務數據 賽門鐵克推出全新信息保護解決方案

最新推出的Symantec Information Centric Security解決方案,能夠幫助企業隨時隨地對數據進行自動加密、跟蹤和撤銷,提供卓越的可見性和管控力 近日,全球網絡安全領域的領導者賽門鐵克公司宣布推出一款全新的高級信息保護工具 Symantec Inform…

leetcode312. 戳氣球(動態規劃)

有 n 個氣球,編號為0 到 n-1,每個氣球上都標有一個數字,這些數字存在數組 nums 中。 現在要求你戳破所有的氣球。如果你戳破氣球 i ,就可以獲得 nums[left] * nums[i] * nums[right] 個硬幣。 這里的 left 和 right 代表和 i 相鄰…

碳鋼腐蝕速率計算公式_鎂合金輪轂螺栓連接的電偶腐蝕行為

環境污染和能源短缺促使日益發達的汽車工業大力推進構件輕量化,鎂合金是最輕的結構材料之一,構件采用鎂合金制造可以在減重的同時不降低結構強度,受到汽車工業的青睞。輪轂作為汽車的主要組成部件,其輕量化是汽車節能減排的有效途…

第七周總結

2019第七周作業 本周作業頭 這個作業屬于那個課程C語言程序設計II這個作業要求在哪里https://edu.cnblogs.com/campus/zswxy/computer-scienceclass1-2018/homework/2939我在這個課程的目標是理解指針數組和地址之前的關系及應用這個作業在那個具體方面幫助我實現目標practice參…

python大綱圖_Python課程大綱

課程大綱被分成6個部分,每個部分又被分解為多個階段, 而每個階段包含了多個Try, Workshop, FactToFace, Apply. 這里只列出部分,和階段:CHAPTER 0 : 預科[可選]Linux使用,常用CMD,服務配置,IDE&…

如何使用Google Authenticator在ASP.NET Core中設置兩因素身份驗證

介紹 (Introduction) In this article, we are going to learn how to perform two-factor authentication in an ASP.NET Core application using the Google Authenticator app.在本文中,我們將學習如何使用Google Authenticator應用程序在ASP.NET Core應用程序中…

280. Wiggle Sort

最后更新 二刷 這個題做得真蠢。上來想的復雜了,想的是quick sort之類的,然后一個一個交換。 實際上直接交換就行。。沒啥特別的。 回頭看一刷也是同樣的思考過程 宿命論啊。。 Time: O(n) Space: O(1) public class Solution {public void wiggleSort(i…

避免人為災難:盤點數據中心里十大愚蠢行為

對于企業運營,數據中心從設計、部署等各個環節都有極其嚴格的規范,保證簡單的“題目”不出錯也需要企業IT管理人員的智慧,在數據中心任何一個小錯誤往往會帶來巨大災難。數據中心從設計、部署、測試、運行、運維等各個環節都不能有任何的疏忽…

python中node.tag的用法_python在ui自動化中的一些常見用法

http://cn.python-requests.org/zh_CN/latest 可以查看requests庫的說明,pprint(res.json(),width30)可以對請求的返回值按照json格式化形式進行打印。常見的content-type 有application/x-www-form-urlencoded、application/json、application/xml。自動化測試操作…

leetcode1039. 多邊形三角剖分的最低得分(動態規劃)

給定 N,想象一個凸 N 邊多邊形,其頂點按順時針順序依次標記為 A[0], A[i], …, A[N-1]。 假設您將多邊形剖分為 N-2 個三角形。對于每個三角形,該三角形的值是頂點標記的乘積,三角剖分的分數是進行三角剖分后所有 N-2 個三角形的…

TRIZ解決問題方法

個人覺的成功是有規律的,那些成功的人士,都有一套處理事情的秘籍。只要我們的思維方式把那些秘籍融會貫通,并快速執行,我們有一天也會成功的。 TRIZ解決問題的5點方法。 1.確定最終目標。 2.列出阻礙因素 3.消除阻礙因素 4.可以利…

windows調用python_windows 快捷調用Python語言

本文主要向大家介紹了windows 快捷調用Python語言,通過具體的內容向大家展示,希望對大家學習Python語言有所幫助。場景1:某云平臺的賬號/或密碼比較長,一旦瀏覽器緩存失效,就要去郵件/文件查找,費時費力場景…

《量化投資:以MATLAB為工具》連載(1)基礎篇-N分鐘學會MATLAB(上)

http://blog.sina.com.cn/s/blog_4cf8aad30102uylf.html 《量化投資:以MATLAB為工具》連載(1)基礎篇-N分鐘學會MATLAB(上) 《量化投資:以MATLAB為工具》簡介 《量化投資:以MATLAB為工具》是由電子工業出版社&#xff0…

android-開源項目_我如何擺脫對開源的恐懼,并開始了自己的項目-以及如何做到。...

android-開源項目by Linea Brink Andersen通過Linea Brink Andersen 我如何擺脫對開源的恐懼,并開始了自己的項目-以及如何做到。 (How I crushed my fear of open source and started my own project — and how you can, too.) A week ago, I started an Open So…

本題要求實現函數輸出n行數字金字塔。_練習5-3 數字金字塔 (15分)

本題要求實現函數輸出n行數字金字塔。函數接口定義&#xff1a;void pyramid( int n );其中n是用戶傳入的參數&#xff0c;為[1, 9]的正整數。要求函數按照如樣例所示的格式打印出n行數字金字塔。注意每個數字后面跟一個空格。裁判測試程序樣例&#xff1a;#include <stdio.…

leetcode167. 兩數之和 II - 輸入有序數組(二分查找)

給定一個已按照升序排列 的有序數組&#xff0c;找到兩個數使得它們相加之和等于目標數。 函數應該返回這兩個下標值 index1 和 index2&#xff0c;其中 index1 必須小于 index2。 說明: 返回的下標值&#xff08;index1 和 index2&#xff09;不是從零開始的。 你可以假設每…

thinkcmf 橫向排列數據_利用python進行數據分析之數據清洗規整

1.處理缺失值數據使用dropna()時&#xff0c;注意里面參數axis、how、thresh的用法使用fillna()時&#xff0c;注意里面參數value、method、inplace、limit的用法2.數據轉換去重data.drop_duplicates(keeplast)#注意keep的用法映射map&#xff08;&#xff09;針對的是一維數組…