Xpath簡介
XPath即為XML路徑語言,它是一種用來確定XML(標准通用標記語言的子集)文檔中某部分位置的語言。XPath基於XML的樹狀結構,有不同類型的節點,包括元素節點,屬性節點和文本節點,提供在數據結構樹中找尋節點的能力。起初 XPath 的提出的初衷是將其作為一個通用的、介於XPointer與XSLT間的語法模型。但是 XPath 很快的被開發者采用來當作小型查詢語言。
簡單來說我們通過Xpath可以獲取XML中的指定元素和指定節點的值。在網絡爬蟲中我們通過會把爬蟲獲取的HTML數據轉換成XML結構,然后通過XPath解析,獲取我們想要的結果。
一.選取節點
二.謂語(Predicates)
謂語用來查找某個特定的節點或者包含某個指定的值的節點。
謂語被嵌在方括號中。
三. 通配符
四.多路徑選擇
通過在路徑表達式中使用“|”運算符,您可以選取若干個路徑。
五.XPath 軸
軸可定義相對於當前節點的節點集。
六.常用的功能函數
使用功能函數能夠更好的進行模糊搜索
import requests from lxml import etree url = 'https://www.qiushibaike.com/' rep = requests.get(url) rep.encoding = rep.apparent_encoding html = etree.HTML(rep.text) res = html.xpath('//div[@class="content"]') # 獲取所有class=content的div res = html.xpath('//div[@class="content"]//span') # 獲取所有class=content的div下的所有span標簽 res = html.xpath('//div[@class="content"]/span') # 獲取所有class=content的div下span標簽(子級) res = html.xpath('//div[@class="content"]')[0] # 獲取第一個div對象 print(res.xpath('../@href')) # ../當前節點的父節點, 獲取當前節點父節點的href屬性 res = html.xpath('//div[@class="content"]//span')[0] # 獲取第一個span對象 print(res.xpath('./parent::*')) # 獲取當前節點的父節點 res = html.xpath('//div[@class="content"]')[0] # 獲取第一個div對象 print(res.xpath('./span/text()')) # # ./當前節點,獲取當前節點下的span節點 res = html.xpath('//div[@class="content"]/child::span') # 獲取所有class=content的div的左右子元素且為span的節點 res = html.xpath('//div[@class="content"]/span/text()') # 獲取文本 res = html.xpath('//div[@class="content"]/@class') # 獲取屬性
七.使用xpath采集糗事百科

from lxml import etree import requests import re import json li = [] for i in range(1, 10): if i == 1: URL = "https://www.qiushibaike.com/" else: URL = "https://www.qiushibaike.com/8hr/page/%s/" % str(i) response = requests.get(URL) response.encoding = 'UTF-8' html = etree.HTML(response.text) # 獲取所有的段子 dz = html.xpath('//div[@id="content-left"]/div') for item in dz: dic = {} # 獲取用戶昵稱 name = item.xpath('.//h2/text()') age = item.xpath('.//div[@class="articleGender womenIcon"]/text()') if not age: age = item.xpath('.//div[@class="articleGender manIcon"]/text()') else: age = None content = item.xpath('.//div[@class="content"]/span')[0] content = content.xpath('string(.)') img_src = item.xpath('.//div[@class="thumb"]//img/@src') # 格式化地址 if img_src: img_src = '%s' + img_src[0] src = img_src % 'https:' dic['src'] = src if age: dic['age'] = age[0].strip() dic['name'] = name[0].strip() dic['content'] = content li.append(dic) data = json.dumps(li, ensure_ascii=False, indent=4) with open('xpath_bk', 'wb') as f: f.write(bytes(data,encoding='utf-8'))