1. 程式人生 > 其它 >爬蟲--資料解析

爬蟲--資料解析

資料解析的目的是獲取區域性的資料

資料解析的方法有正則,xpath,bs4

正則:https://www.cnblogs.com/l1222514/p/11011009.html

正則解析:
  import re
  #正則獲取定位 可以獲取括號裡面的內容
  ex='xxxxx(.*?)xxxx'
  re.findall(ex,page_text,re.S)

bs4解析
 解析原理:
  例項化一個Beautifulsoup的物件,且將頁面原始碼資料載入到該物件中
  使用該物件的相關屬性和方法實現標籤定位和資料提取
環境的安裝:
  pip install bs4
  pip install lxml
例項化Beautifulsoup物件
  BeautifulSoup(page_text,'lxml'):將從網際網路上請求到的頁面原始碼資料載入到該物件中
  BeautifulSoup(fp,'lxml'):將本地儲存的一樣頁面原始碼資料載入到該物件中

bs4的方法:
  from bs4 import BeautifulSoup
  soup = BeautifulSoup(fp,'lxml')
方法1#soup.tagName:只可以定位到第一次出現的tagName標籤
  soup.title
  soup.div
方法2#soup.find(‘tagName’)
  soup.find('a') # ==soup.a
方法3#屬性定位
  soup.find('div',class_='song')
方法4#find_all
  soup.find_all('div')[2]
方法5#select('選擇器') 選擇器中class用.表示
  ‘>’:表示一個層級 空格:表示多個層級
  soup.select('.song')
  soup.select('.tang > ul > li > a') #==soup.select('.tang a')

獲取文字的方法##取文字:string取的是直系的文字資料,text獲取的是全部的資料
  soup.p.string
  soup.find('div',class_='tang').get_text() #==soup.find('div',class_='tang').text
獲取屬性的方法#取屬性
  soup.a['href']
  soup.select('.tang > ul > li > a')[0]['href']

xpath解析:
  解析效率比較高
  通用性最強的

環境安裝:pip install lxml
解析原理:
  例項化一個etree物件且將即將被解析的頁面原始碼資料載入到該物件中
  使用etree物件中的xpath方法結合著xpath表示式進行標籤定位和資料提取
例項化etree物件
  etree.parse('本地檔案路徑')
  etree.HTML(page_text)


xpath定位方法:
  from lxml import etree
  tree = etree.parse('./test.html')
方法1:#定位title標籤
  #第一個/表示根目錄
  tree.xpath('/html/head/title')
  tree.xpath('/html//title')
  tree.xpath('//title')
方法2:#定位class=song的div
  tree.xpath('//div[@class="song"]')
  tree.xpath('//div[2]') #xpath表示式中的索引是從1開始
  tree.xpath('//div[@class="tang"]/ul/li[4]/a') #==tree.xpath('//div[@class="tang"]//li[4]/a')

方法3:#取文字(獲取李清照)
  /text() 獲取直系文字 //text() 獲取標籤下的所有文字
  tree.xpath('//div[@class="song"]/p[1]/text()')[0]
  tree.xpath('//div[@class="song"]/text()')
方法4:#取屬性 /@屬性

  tree.xpath('//a/@href')