往期內容提要:
- [Python爬蟲] 一、爬蟲原理之HTTP和HTTPS的請求與響應
- [Python爬蟲] 二、爬蟲原理之定義、分類、流程與編碼格式
- [Python爬蟲] 三、數據抓取之Requests HTTP 庫
- [Python爬蟲] 四、數據抓取之HTTP/HTTPS抓包工具Fiddler
- [Python爬蟲] 五、數據提取之正則表達式re模塊
- [Python爬蟲] 六、數據提取之XPath與lxml類庫
一、非結構化數據與結構化數據
一般來講對我們而言,需要抓取的是某個網站或者某個應用的內容,提取有用的價值。內容一般分爲兩部分,非結構化的數據 和 結構化的數據。
- 非結構化數據:先有數據,再有結構。
- 結構化數據:先有結構、再有數據。
- 不同類型的數據,我們需要採用不同的方式來處理。
處理方式 | 非結構化數據 | 結構化數據 |
---|---|---|
正則表達式 | 文本、電話號碼、郵箱地址、HTML 文件 | XML 文件 |
XPath | HTML 文件 | XML 文件 |
CSS選擇器 | HTML 文件 | XML 文件 |
JSON Path | JSON 文件 | |
轉化成Python類型 | JSON 文件(json類)、XML 文件(xmltodict) |
在介紹完正則表達式、XPath、CSS選擇器後,我們最後在數據提取板塊再學習瞭解結構化數據提取之JSON與JsonPATH。
二、瞭解JSON
JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式,它使得人們很容易的進行閱讀和編寫。同時也方便了機器進行解析和生成。適用於進行數據交互的場景,比如網站前臺與後臺之間的數據交互。
JSON和XML的比較可謂不相上下。
Python 2.7中自帶了JSON模塊,直接import json
就可以使用了。
官方文檔:http://docs.python.org/library/json.html
json簡單說就是javascript中的對象和數組,所以這兩種結構就是對象和數組兩種結構,通過這兩種結構可以表示各種複雜的結構
對象:對象在js中表示爲
{ }
括起來的內容,數據結構爲{ key:value, key:value, ... }
的鍵值對的結構,在面向對象的語言中,key爲對象的屬性,value爲對應的屬性值,所以很容易理解,取值方法爲 對象.key 獲取屬性值,這個屬性值的類型可以是數字、字符串、數組、對象這幾種。數組:數組在js中是中括號
[ ]
括起來的內容,數據結構爲["Python", "javascript", "C++", ...]
,取值方式和所有語言中一樣,使用索引獲取,字段值的類型可以是 數字、字符串、數組、對象幾種。
import-jsonjson
模塊提供了四個功能:dumps
、dump
、loads
、load
,用於字符串 和 python數據類型間進行轉換。
方法 | 功能 |
---|---|
json.loads | 把Json格式字符串解碼轉換成Python對象 |
json.dumps | 實現python類型轉化爲json字符串,返回一個str對象 把一個Python對象編碼轉換成Json字符串 |
json.load | 讀取文件中json形式的字符串元素 轉化成python類型 |
json.dump | 將Python內置類型序列化爲json對象後寫入文件 |
(1) json.loads()
把Json格式字符串解碼轉換成Python對象
# json_loads.py
import json
strList = '[1, 2, 3, 4]'
strDict = '{"city": "北京", "name": "大貓"}'
json.loads(strList)
# [1, 2, 3, 4]
json.loads(strDict) # json數據自動按Unicode存儲
# {u'city': u'\u5317\u4eac', u'name': u'\u5927\u732b'}
(2) json.dumps()
實現python類型轉化爲json字符串,返回一個str對象把一個Python對象編碼轉換成Json字符串
# json_dumps.py
import json
import chardet
listStr = [1, 2, 3, 4]
tupleStr = (1, 2, 3, 4)
dictStr = {"city": "北京", "name": "大貓"}
json.dumps(listStr)
# '[1, 2, 3, 4]'
json.dumps(tupleStr)
# '[1, 2, 3, 4]'
# 注意:json.dumps() 序列化時默認使用的ascii編碼
# 添加參數 ensure_ascii=False 禁用ascii編碼,按utf-8編碼
# chardet.detect()返回字典, 其中confidence是檢測精確度
json.dumps(dictStr)
# '{"city": "\\u5317\\u4eac", "name": "\\u5927\\u5218"}'
chardet.detect(json.dumps(dictStr))
# {'confidence': 1.0, 'encoding': 'ascii'}
print json.dumps(dictStr, ensure_ascii=False)
# {"city": "北京", "name": "大劉"}
chardet.detect(json.dumps(dictStr, ensure_ascii=False))
# {'confidence': 0.99, 'encoding': 'utf-8'}
chardet是一個非常優秀的編碼識別模塊,可通過pip安裝
(3) json.load()
讀取文件中json形式的字符串元素 轉化成python類型
# json_load.py
import json
strList = json.load(open("listStr.json"))
print strList
# [{u'city': u'\u5317\u4eac'}, {u'name': u'\u5927\u5218'}]
strDict = json.load(open("dictStr.json"))
print strDict
# {u'city': u'\u5317\u4eac', u'name': u'\u5927\u5218'}
(4) json.dump()
將Python內置類型序列化爲json對象後寫入文件
# json_dump.py
import json
listStr = [{"city": "北京"}, {"name": "大劉"}]
json.dump(listStr, open("listStr.json","w"), ensure_ascii=False)
dictStr = {"city": "北京", "name": "大劉"}
json.dump(dictStr, open("dictStr.json","w"), ensure_ascii=False)
(5) Json豆瓣爬蟲
# coding=utf-8
import requests
import json
class DoubanSpider:
def __init__(self):
self.url_temp_list = [
{
"url_temp": "https://m.douban.com/rexxar/api/v2/subject_collection/filter_tv_american_hot/items?start={}&count=18&loc_id=108288",
"country": "US"
},
{
"url_temp": "https://m.douban.com/rexxar/api/v2/subject_collection/filter_tv_english_hot/items?start={}&count=18&loc_id=108288",
"country": "UK"
},
{
"url_temp": "https://m.douban.com/rexxar/api/v2/subject_collection/filter_tv_domestic_hot/items?start={}&count=18&loc_id=108288",
"country": "CN"
}
]
self.headers = {
"User-Agent": "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Mobile Safari/537.36"}
def parse_url(self, url): # 發送請求,獲取響應
print(url)
response = requests.get(url, headers=self.headers)
return response.content.decode()
def get_content_list(self, json_str): # 提取是數據
dict_ret = json.loads(json_str) # 將json文件轉化爲Python文件
content_list = dict_ret["subject_collection_items"]
total = dict_ret["total"]
return content_list, total
def save_content_list(self, content_list,country): # 保存
with open("douban.txt", "a", encoding="utf-8") as f:
for content in content_list:
content["country"] = country
f.write(json.dumps(content, ensure_ascii=False))
f.write("\n") # 寫入換行符,進行換行
print("保存成功")
def run(self): # 實現主要邏輯
for url_temp in self.url_temp_list:
num = 0
total = 100 # 假設有第一頁
while num < total + 18:
# 1.start_url
url = url_temp["url_temp"].format(num)
# 2.發送請求,獲取響應
json_str = self.parse_url(url)
# 3.提取是數據
content_list, total = self.get_content_list(json_str)
# 4.保存
self.save_content_list(content_list,url_temp["country"])
# if len(content_list)<18:
# break
# 5.構造下一頁的url地址,進入循環
num += 18
if __name__ == '__main__':
douban_spider = DoubanSpider()
douban_spider.run()
三、JsonPath
JsonPath 是一種信息抽取類庫,是從JSON文檔中抽取指定信息的工具,提供多種語言實現版本,包括:Javascript, Python, PHP 和 Java。
JsonPath 對於 JSON 來說,相當於 XPATH 對於 XML。
下載地址:https://pypi.python.org/pypi/jsonpath
安裝方法:點擊
Download URL
鏈接下載jsonpath,解壓之後執行python setup.py install
(1) JsonPath與XPath語法對比:
Json結構清晰,可讀性高,複雜度低,非常容易匹配,下表中對應了XPath的用法。
XPath | JSONPath | 描述 |
---|---|---|
/ |
$ |
根節點 |
. |
@ |
現行節點 |
/ |
. or[] |
取子節點 |
.. |
n/a | 取父節點,Jsonpath未支持 |
// |
.. |
就是不管位置,選擇所有符合條件的條件 |
* |
* |
匹配所有元素節點 |
@ |
n/a | 根據屬性訪問,Json不支持,因爲Json是個Key-value遞歸結構,不需要。 |
[] |
[] |
迭代器標示(可以在裏邊做簡單的迭代操作,如數組下標,根據內容選值等) |
| | [,] |
支持迭代器中做多選。 |
[] |
?() |
支持過濾操作. |
n/a | () |
支持表達式計算 |
() |
n/a | 分組,JsonPath不支持 |
(2) 示例:
我們以拉勾網城市JSON文件 爲例,獲取所有城市。
# jsonpath_lagou.py
import requests
import jsonpath
import json
import chardet
url = 'http://www.lagou.com/lbs/getAllCitySearchLabels.json'
response = equests.get(url)
html = response.text
# 把json格式字符串轉換成python對象
jsonobj = json.loads(html)
# 從根節點開始,匹配name節點
citylist = jsonpath.jsonpath(jsonobj,'$..name')
print citylist
print type(citylist)
fp = open('city.json','w')
content = json.dumps(citylist, ensure_ascii=False)
print content
fp.write(content.encode('utf-8'))
fp.close()
後期內容提要:
- [Python爬蟲] 八、動態HTML處理之Selenium與PhantomJS
- [Python爬蟲] 九、機器視覺與機器圖像識別之Tesseract
- [Python爬蟲] 十、Scrapy 框架
如果您有任何疑問或者好的建議,期待你的留言與評論!