數據解析方式
- 正則
- xpath
- bs4
數據解析的原理:
- 標簽的定位
- 提取標簽中存儲的文本數據或者標簽屬性中存儲的數據
正則
# 正則表達式
單字符:
. : 除換行以外所有字符
[] :[aoe] [a-w] 匹配集合中任意一個字符
\d :數字 [0-9]
\D : 非數字
\w :數字、字母、下划線、中文
\W : 非\w
\s :所有的空白字符包,括空格、制表符、換頁符等等。等價於 [ \f\n\r\t\v]。
\S : 非空白
數量修飾:
* : 任意多次 >=0
+ : 至少1次 >=1
? : 可有可無 0次或者1次
{m} :固定m次 hello{3,}
{m,} :至少m次
{m,n} :m-n次
邊界:
$ : 以某某結尾
^ : 以某某開頭
分組:
(ab)
貪婪模式: .*
非貪婪(惰性)模式: .*?
re.I : 忽略大小寫
re.M :多行匹配
re.S :單行匹配
re.sub(正則表達式, 替換內容, 字符串)
#爬取糗事百科中所有的糗圖圖片數據
import os
import requests
import re
from urllib import request
if not os.path.exists('./qiutu'):
os.mkdir('./qiutu')
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
url = 'https://www.qiushibaike.com/pic/'
page_text = requests.get(url=url,headers=headers).text
ex = '<div class="thumb">.*?<img src="(.*?)" alt.*?</div>'
img_url = re.findall(ex,page_text,re.S)
for url in img_url:
url = 'https:'+url
img_name = url.split('/')[-1]
img_path = './qiutu/'+img_name
request.urlretrieve(url,img_path)
print(img_name,'下載成功!!!')
bs4解析
-
解析原理:
- 實例化一個Beautifulsoup的對象,且將頁面源碼數據加載到該對象中
- 使用該對象的相關屬性和方法實現標簽定位和數據提取
-
環境的安裝:
- pip install bs4
- pip install lxml
-
實例化Beautifulsoup對象
- BeautifulSoup(page_text,'lxml'):將從互聯網上請求到的頁面源碼數據加載到該對象中
- BeautifulSoup(fp,'lxml'):將本地存儲的一樣頁面源碼數據加載到該對象中
soup.a.attrs 返回一字典,里面是所有屬性和值
soup.a['href'] 獲取href屬性
soup.a.string
soup.a.text
soup.a.get_text()
#find只能找到符合要求的第一個標簽,他返回的是一個對象
soup.find('a')
soup.find('a', class_='xxx')
soup.find('a', title='xxx')
soup.find('a', id='xxx')
soup.find('a', id=re.compile(r'xxx'))
#返回一個列表,列表里面是所有的符合要求的對象
soup.find_all('a')
soup.find_all('a', class_='wang')
soup.find_all('a', id=re.compile(r'xxx'))
soup.find_all('a', limit=2) #提取出前兩個符合要求的a
#選擇,選擇器 css中
常用的選擇器
標簽選擇器、id選擇器、類選擇器
層級選擇器**
div h1 a 后面的是前面的子節點即可
div > h1 > a 后面的必須是前面的直接子節點
屬性選擇器
input[name='hehe']
select('選擇器的')
返回的是一個列表,列表里面都是對象
find find_all select不僅適用於soup對象,還適用於其他的子對象,如果調用子對象的select方法,那么就是從這個子對象里面去找符合這個選擇器的標簽
#爬取古詩文網的三國演義小說
url = 'http://www.shicimingju.com/book/sanguoyanyi.html'
page_text = requests.get(url=url,headers=headers).text
#數據解析:標題和url
soup = BeautifulSoup(page_text,'lxml')
li_list = soup.select('.book-mulu > ul > li')
fp = open('./sanguo.txt','w',encoding='utf-8')
for li in li_list:
title = li.a.string
detail_url = 'http://www.shicimingju.com'+li.a['href']
#單獨對詳情頁發起請求獲取源碼數據
detail_page_text = requests.get(url=detail_url,headers=headers).text
soup = BeautifulSoup(detail_page_text,'lxml')
content = soup.find('div',class_="chapter_content").text
fp.write(title+'\n'+content+'\n')
print(title,':下載成功!')
fp.close()
xpath解析:
- 解析效率比較高
- 通用性最強的
- 環境安裝:pip install lxml
- 解析原理:
- 實例化一個etree對象且將即將被解析的頁面源碼數據加載到該對象中
- 使用etree對象中的xpath方法結合着xpath表達式進行標簽定位和數據提取
- 實例化etree對象
- etree.parse('本地文件路徑')
- etree.HTML(page_text)
#爬取全國城市名稱
import requests
from lxml import etree
# UA偽裝
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
url = 'https://www.aqistudy.cn/historydata/'
page_text = requests.get(url=url,headers=headers).text
tree = etree.HTML(page_text)
# hot_city = tree.xpath('//div[@class="bottom"]/ul/li/a/text()')
# all_city = tree.xpath('//div[@class="bottom"]/ul/div[2]/li/a/text()')
# all_city
tree.xpath('//div[@class="bottom"]/ul/div[2]/li/a/text() | //div[@class="bottom"]/ul/li/a/text()'
