1. 程式人生 > 其它 >Xpath解析

Xpath解析

技術標籤:python爬蟲

xpath解析:最常用且比較便捷的一種解析方式。通用性

  • xpath解析原理:
    • –1.例項化一個etree物件,且將且需要將解析的頁面的資料載入到該物件中。
    • –2.呼叫etree物件中的xpath方法結合著xpath表示式實現標籤的定位和內容的捕獲。
  • 環境的安裝
    • 1.cmd方法
      pip install lxml
    • 直接在pycharm中直接安裝(更簡單)
  • 如何例項化一個物件
    • –1.將本地文件中的原始碼載入帶etree物件中:
      etree.parse(‘fileName’)
    • –2.可以從網際網路上獲取的原始碼載入到該物件中
      etree.HTML(‘fileName’)
    • – 3.xpath表示式
  • xpath表示式(重點)
    • — /:表示的是從根節點開始定位。表示是一個層級。
      r = tree.xpath(’/html/div/p’)
    • — //:表示的是多個層級。可以表示從任意位置開始定位。
      #r = tree.xpath(’//p’)
      #r = tree.xpath(’/html//p’)
    • —屬性定位:
      //div[@class=‘song’] ---->tag[@attrName=“attrValue”]
    • — 索引定位:
      //div[@class=“song”]/p[3] 索引是從1開始的。
    • — 取文字:
      - /text() 獲取的是標籤中直系的文字內容
      - //text() 標籤中非直系的文字內容(所有的文字內容)
    • — 取屬性:
      /@attrName ==>img/src
      r = tree.xpath(’//div[@class=“tang”]//li[3]/a/@href’)[0]

例子:

from lxml import etree
if __name__ == "__main__":
    tree = etree.parse('test.html')
    #r=tree.xpath('/html/head/)
    #r = tree.xpath('/html//p')
    #r = tree.xpath('//p')
    r = tree.xpath('//div[@class="tang"]//li[3]/a/@href'
)[0] print(r)

例項1:58同城

import requests
from lxml import etree
if __name__ == "__main__":
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'
    }
    url='https://zz.58.com/ershoufang/?PGTID=0d200001-0015-6095-00a5-32e38bd5575e&ClickID=1'
    response = requests.get(url=url,headers=headers).text
    li_list = etree.HTML(response)
    list_all=li_list.xpath('//div[@class="property-content"]')
    fp = open('58.txt', 'w', encoding='utf-8')
    for list in list_all:
        title = list.xpath('./div[@class="property-content-detail"]//h3/text()')[0]
        money= list.xpath('./div[@class="property-price"]/p/span[@class="property-price-total-num"]/text()')[0]
        print(title,money+"萬")
        fp.write(title)
        fp.write(money+"萬"+"/n")

案例2:全國城市名字

import requests
from lxml import etree
if __name__ == "__main__":
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'
    }
    url='https://www.aqistudy.cn/historydata/'
    City_list = requests.get(url=url,headers=headers).text
    tree = etree.HTML(City_list)
    city_list = tree.xpath('//div[@class="bottom"]/ul/li/a | //div[@class="bottom"]/ul/div[2]/li/a')
    ALL_city=[]
    for a in city_list:
        city_N = a.xpath('./text()')[0]
        ALL_city.append(city_N)
    print(ALL_city,len(ALL_city))

其中’//div[@class=“bottom”]/ul/li/a | //div[@class=“bottom”]/ul/div[2]/li/a’重點,兩者皆可以。