在线不卡日本ⅴ一区v二区_精品一区二区中文字幕_天堂v在线视频_亚洲五月天婷婷中文网站

  • <menu id="lky3g"></menu>
  • <style id="lky3g"></style>
    <pre id="lky3g"><tt id="lky3g"></tt></pre>

    Python爬蟲(chóng)之xpath語(yǔ)法及案例使用

    Python爬蟲(chóng)之xpath語(yǔ)法及案例使用

    我們?cè)趯?xiě)Python爬蟲(chóng)時(shí),經(jīng)常需要對(duì)網(wǎng)頁(yè)提取信息,如果用傳統(tǒng)正則表達(dá)去寫(xiě)會(huì)增加很多工作量,此時(shí)需要一種對(duì)數(shù)據(jù)解析的方法,也就是本章要介紹的Xpath表達(dá)式

    Xpath是什么

    XPath,全稱(chēng) XML Path Language,即 XML 路徑語(yǔ)言,它是一門(mén)在 XML 文檔中查找信息的語(yǔ)言。最初是用來(lái)搜尋 XML 文檔的,但同樣適用于 HTML 文檔的搜索。所以在做爬蟲(chóng)時(shí)完全可以使用 XPath 做相應(yīng)的信息抽取。

    XPath 的選擇功能十分強(qiáng)大,它提供了非常簡(jiǎn)潔明了的路徑選擇表達(dá)式。另外,它還提供超過(guò) 100 個(gè)內(nèi)置函數(shù),用于字符串、數(shù)值、時(shí)間的匹配以及節(jié)點(diǎn)、序列的處理等,幾乎所有想要定位的節(jié)點(diǎn)都可以用 XPath 來(lái)選取。

    下面介紹實(shí)戰(zhàn)中常用的幾個(gè)知識(shí)點(diǎn),詳細(xì)也可以看W3C介紹:https://www.w3school.com.cn/xpath/index.asp

    Xpath語(yǔ)法介紹

    路徑常用規(guī)則

    表達(dá)式

    描述

    實(shí)例

    nodename

    選取此節(jié)點(diǎn)的所有子節(jié)點(diǎn)

    xpath(‘//p’)

    選取了p節(jié)點(diǎn)的所有子節(jié)點(diǎn)

    /

    從根節(jié)點(diǎn)選取

    xpath(‘/p’)

    從根節(jié)點(diǎn)上選取p節(jié)點(diǎn)

    //

    選取所有當(dāng)前節(jié)點(diǎn),不考慮位置

    xpath(‘//p’)

    選取所有的p節(jié)點(diǎn)

    .

    選取當(dāng)前節(jié)點(diǎn)

    xpath(‘./p’)

    選取當(dāng)前節(jié)點(diǎn)下的p節(jié)點(diǎn)

    ..

    選取當(dāng)前節(jié)點(diǎn)的父節(jié)點(diǎn)

    xpath(‘..’)

    回到上一個(gè)節(jié)點(diǎn)

    @

    選取屬性

    xpath(’//@calss’)

    選取所有的class屬性

    謂語(yǔ)規(guī)則

    謂語(yǔ)被嵌在方括號(hào)內(nèi),用來(lái)查找某個(gè)特定的節(jié)點(diǎn)或包含某個(gè)制定的值的節(jié)點(diǎn)

    表達(dá)式

    結(jié)果

    xpath(‘/body/p[1]’)

    選取body下的第一個(gè)p節(jié)點(diǎn)

    xpath(‘/body/p[last()]’)

    選取body下最后一個(gè)p節(jié)點(diǎn)

    xpath(‘/body/p[last()-1]’)

    選取body下倒數(shù)第二個(gè)p節(jié)點(diǎn)

    xpath(‘/body/p[positon() ]’)

    選取body下前兩個(gè)p節(jié)點(diǎn)

    xpath(‘/body/p[@class]’)

    選取body下帶有class屬性的p節(jié)點(diǎn)

    xpath(‘/body/p[@class=”main”]’)

    選取body下class屬性為main的p節(jié)點(diǎn)

    xpath(‘/body/p[price>35.00]’)

    選取body下price元素值大于35的p節(jié)點(diǎn)

    通配符

    通配符來(lái)選取未知的XML元素

    表達(dá)式

    結(jié)果

    xpath(’/p/*’)

    選取p下的所有子節(jié)點(diǎn)

    xpath(‘/p[@*]’)

    選取所有帶屬性的p節(jié)點(diǎn)

    取多個(gè)路徑

    使用“|”運(yùn)算符可以選取多個(gè)路徑

    表達(dá)式

    結(jié)果

    xpath(‘//p|//table’)

    選取所有的p和table節(jié)點(diǎn)

    功能函數(shù)

    使用功能函數(shù)能夠更好的進(jìn)行模糊搜索

    函數(shù)

    用法

    解釋

    starts-with

    xpath(‘//p[starts-with(@id,”ma”)]’)

    選取id值以ma開(kāi)頭的p節(jié)點(diǎn)

    contains

    xpath(‘//p[contains(@id,”ma”)]’)

    選取id值包含ma的p節(jié)點(diǎn)

    and

    xpath(‘//p[contains(@id,”ma”) and contains(@id,”in”)]’)

    選取id值包含ma和in的p節(jié)點(diǎn)

    text()

    xpath(‘//p[contains(text(),”ma”)]’)

    選取節(jié)點(diǎn)文本包含ma的p節(jié)點(diǎn)

    語(yǔ)法熟悉

    下面舉一段HTML文本進(jìn)行語(yǔ)法熱身,代碼如下

    #!/usr/bin/env python# -*- coding: utf-8 -*-# time: 2022/8/8 0:05# author: gangtie# email: 648403020@qq.comfrom lxml import etreetext = ”’

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

    ”’# 調(diào)用HTML類(lèi)進(jìn)行初始化,這樣就成功構(gòu)造了一個(gè)XPath解析對(duì)象。# 利用etree.HTML解析字符串page = etree.HTML(text) print(type(page))

    可以看到打印結(jié)果已經(jīng)變成XML元素:

    字符串轉(zhuǎn)換HTML

    字符串利用etree.HTML解析成html格式:

    print(etree.tostring(page,encoding=’utf-8′).decode(‘utf-8’))“`

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

    Process finished with exit code 0“`

    經(jīng)過(guò)處理可以看到缺失的

    也自動(dòng)補(bǔ)全了,還自動(dòng)添加html、body節(jié)點(diǎn)。

    查找絕對(duì)路徑

    通過(guò)絕對(duì)路徑獲取a標(biāo)簽的所有內(nèi)容

    a = page.xpath(“/html/body/p/ul/li/a”)for i in a: print(i.text)“`first itemsecond itemthird itemNonefifth item“`

    查找相對(duì)路徑(常用)

    查找所有l(wèi)i標(biāo)簽下的a標(biāo)簽內(nèi)容

    html = etree.HTML(text)a = html.xpath(“//a/text()”)print(a)“`[‘first item’, ‘second item’, ‘third item’, ‘fifth item’]“`

    當(dāng)前標(biāo)簽節(jié)點(diǎn)

    . 表示選取當(dāng)前標(biāo)簽的節(jié)點(diǎn)。

    我們先定位 ul 元素節(jié)點(diǎn)得到一個(gè)列表,打印當(dāng)前節(jié)點(diǎn)列表得到第一個(gè) ul,接著打印 ul 節(jié)點(diǎn)的子節(jié)點(diǎn) li,text()輸出。

    page = etree.HTML(text)ul = page.xpath(“//ul”)print(ul)print(ul[0].xpath(“.”))print(ul[0].xpath(“./li”))print(ul[0].xpath(“./li/a/text()”))“`[][][, , , , ][‘first item’, ‘second item’, ‘third item’, ‘fifth item’]“`

    父節(jié)點(diǎn)

    .. 表示選取當(dāng)前標(biāo)簽的父節(jié)點(diǎn)。

    可以看到得到ul的上一級(jí)p

    page = etree.HTML(text)ul = page.xpath(“//ul”)print(ul[0].xpath(“.”))print(ul[0].xpath(“..”))“`[][]“`

    屬性匹配

    匹配時(shí)可以用@符號(hào)進(jìn)行屬性過(guò)濾查找a標(biāo)簽下屬性href值為link2.html的內(nèi)容

    html = etree.HTML(text)a = html.xpath(“//a[@href=’link2.html’]/text()”)print(a)“`[‘second item’]“`

    函數(shù)

    last():查找最后一個(gè)li標(biāo)簽里的a標(biāo)簽的href屬性

    html = etree.HTML(text)a = html.xpath(“//li[last()]/a/text()”)print(a)“`[‘fifth item’]“`

    contains:查找a標(biāo)簽中屬性href包含link的節(jié)點(diǎn),并文本輸出

    html = etree.HTML(text)a = html.xpath(“//a[contains(@href, ‘link’)]/text()”)print(a)“`[‘first item’, ‘second item’, ‘third item’, ‘fifth item’]“`

    實(shí)戰(zhàn)案例

    上面說(shuō)完基本用法,接下來(lái)做幾個(gè)實(shí)戰(zhàn)案例練練手。

    案例一:豆瓣讀書(shū)

    # -*-coding:utf8 -*-# 1.請(qǐng)求并提取需要的字段# 2.保存需要的數(shù)據(jù)import requestsfrom lxml import etreeclass DoubanBook(): def __init__(self): self.base_url = ‘https://book.douban.com/chart?subcat=all&icn=index-topchart-popular’ self.headers = { ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ‘ ‘Chrome/104.0.0.0 Safari/537.36’ } # 請(qǐng)求并提取需要的字段 def crawl(self): res = requests.get(self.base_url, headers=self.headers) lis = etree.HTML(res.text).xpath(‘//*[@id=”content”]/p/p[1]/ul/li’) # print(type(lis)) books = [] for li in lis: # print(etree.tostring(li,encoding=’utf-8′).decode(‘utf-8′)) # print(“==================================================”) title = “”.join(li.xpath(“.//a[@class=’fleft’]/text()”)) score = “”.join(li.xpath(“.//p[@class=’clearfix w250′]/span[2]/text()”)) # list輸出帶有[‘ 劉瑜 / 2022-4 / 廣西師范大學(xué)出版社 / 82.00元 / 精裝 ‘] publishing = “”.join(li.xpath(“.//p[@class=’subject-abstract color-gray’]/text()”)).strip() book = { ‘title’: title, ‘score’: score, ‘publishing’: publishing, } books.append(book) self.save_data(books) def save_data(self, datas): with open(‘books.txt’, ‘w’, encoding=’utf-8′) as f: f.write(str(datas)) def run(self): self.crawl()if __name__ == ‘__main__’: DoubanBook().run()

    案例二:彼岸圖片下載

    #!/usr/bin/env python# -*- coding: utf-8 -*-# author: 鋼鐵知識(shí)庫(kù)# email: 648403020@qq.comimport osimport requestsfrom lxml import etree# 彼岸圖片下載class BiAn(): def __init__(self): self.url = ‘https://pic.netbian.com’ self.headers = { ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ‘ ‘Chrome/104.0.0.0 Safari/537.36’, ‘cookie’: ‘__yjs_duid=1_cb922eedbda97280755010e53b2caca41659183144320; Hm_lvt_c59f2e992a863c2744e1ba985abaea6c=1649863747,1660203266; zkhanecookieclassrecord=%2C23%2C54%2C55%2C66%2C60%2C; Hm_lpvt_c59f2e992a863c2744e1ba985abaea6c=1660207771; yjs_js_security_passport=1225f36e8501b4d95592e5e7d5202f4081149e51_1630209607_js’ } # 如果目錄不存在會(huì)報(bào)錯(cuò) if not os.path.exists(‘BianPicture’): os.mkdir(‘BianPicture’) # 請(qǐng)求拿到ul列表 def crawl(self): res = requests.get(self.url, headers=self.headers) res.encoding = ‘gbk’ uls = etree.HTML(res.text).xpath(‘//p[@class=”slist”]/ul[@class=”clearfix”]/li’) # print(etree.tostring(uls,encoding=’gbk’).decode(‘gbk’)) # 循環(huán)拿到圖片名、圖片地址,拼接請(qǐng)求再次下載到圖片 for ul in uls: img_name = ul.xpath(‘.//a/b/text()’)[0] img_src = ul.xpath(‘.//a/span/img/@src’)[0] # print(img_name + img_src) img_url = self.url + img_src # 拼接后下載圖片,轉(zhuǎn)義Bytes img_res = requests.get(img_url, headers=self.headers).content img_path = “BianPicture/” + img_name + “.jpg” data = { ‘img_res’: img_res, ‘img_path’: img_path } self.save_data(data) # 數(shù)據(jù)保存邏輯 def save_data(self, data): with open(data[‘img_path’], ‘wb’) as f: f.write(data[‘img_res’]) # print(data) def run(self): self.crawl()if __name__ == ‘__main__’: BiAn().run()

    案例三:全國(guó)城市名稱(chēng)爬取

    #!/usr/bin/env python# -*- coding: utf-8 -*-# author: 鋼鐵知識(shí)庫(kù)# email: 648403020@qq.comimport osimport requestsfrom lxml import etreeclass CityName(): def __init__(self): self.url = ‘https://www.aqistudy.cn/historydata/’ self.headers = { ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36’ } # 判斷目錄是否存在 if not os.path.exists(‘city_project’): os.mkdir(‘city_project’) def crawl(self): res = requests.get(url=self.url, headers=self.headers).text uls = etree.HTML(res).xpath(‘//p[@class=”all”]/p[2]/ul/p[2]/li’) all_city_name = list() for ul in uls: city_name = ul.xpath(‘.//a/text()’)[0] # print(type(city_name)) all_city_name.append(city_name) self.save_data(all_city_name) def save_data(self, data): with open(‘./city_project/city.txt’, ‘w’) as f: f.write(str(data)) def run(self): self.crawl()if __name__ == ‘__main__’: CityName().run()

    xpath使用工具

    chrome生成XPath表達(dá)式

    經(jīng)常使用chome的朋友都應(yīng)該知道這功能,在 審查 狀態(tài)下(快捷鍵ctrl+shift+i,F(xiàn)12),定位到元素(快捷鍵ctrl+shift+c) ,在Elements選項(xiàng)卡中,右鍵元素 Copy->Copy xpath,就能得到該元素的xpath了

    Xpath Helper插件

    為chome裝上XPath Helper就可以很輕松的檢驗(yàn)自己的xpath是否正確了。安裝插件需要特別上網(wǎng),安裝好插件后,在chrome右上角點(diǎn)插件的圖標(biāo),調(diào)出插件的黑色界面,編輯好xpath表達(dá)式,表達(dá)式選中的元素被標(biāo)記為黃色

    —- 鋼鐵俠的知識(shí)庫(kù) 2022.08.15

    結(jié)語(yǔ):

    以上就是利用XPath的所有用法,從常用語(yǔ)法,到案例練習(xí)都走了一遍。下一章 鋼鐵知識(shí)庫(kù) 會(huì)繼續(xù)介紹另一種好用的解析框架,Beautiful Soup

    文章來(lái)自https://www.cnblogs.com/jiba/p/16589856.html

    鄭重聲明:本文內(nèi)容及圖片均整理自互聯(lián)網(wǎng),不代表本站立場(chǎng),版權(quán)歸原作者所有,如有侵權(quán)請(qǐng)聯(lián)系管理員(admin#wlmqw.com)刪除。
    上一篇 2022年8月17日 12:12
    下一篇 2022年8月17日 12:12

    相關(guān)推薦

    聯(lián)系我們

    聯(lián)系郵箱:admin#wlmqw.com
    工作時(shí)間:周一至周五,10:30-18:30,節(jié)假日休息