Python爬蟲開發【第1篇】【Json與JsonPath】

來源:互聯網
上載者:User

標籤:安裝方法   1.2   path   方法   編碼格式   xpath文法   序列化   target   案例   

JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式,它使得人們很容易的進行閱讀和編寫。同時也方便了機器進行解析和產生。適用於進行資料互動的情境,比如網站前台與後台之間的資料互動。

官方文檔:http://docs.python.org/library/json.html

Json線上解析網站:http://www.json.cn/#

 

JSON

json簡單說就是javascript中的對象和數組,所以這兩種結構就是對象和數組兩種結構,通過這兩種結構可以表示各種複雜的結構

  1. 對象:對象在js中表示為{ }括起來的內容,資料結構為 { key:value, key:value, ... }的索引值對的結構,在物件導向的語言中,key為對象的屬性,value為對應的屬性值,所以很容易理解,取值方法為 對象.key 擷取屬性值,這個屬性值的類型可以是數字、字串、數組、對象這幾種。

  2. 數組:數組在js中是中括弧[ ]括起來的內容,資料結構為 ["Python", "javascript", "C++", ...],取值方式和所有語言中一樣,使用索引擷取,欄位值的類型可以是 數字、字串、數組、對象幾種。

1、import json

json模組提供了四個功能:dumpsdumploadsload,用於字串 和 python資料類型間進行轉換。

1.1、 json.loads()

把Json格式字串解碼轉換成Python對象 從json到python的類型轉化對照如下:

# json_loads.pyimport jsonstrList = ‘[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‘}
1.2、json.dumps()

實現python類型轉化為json字串,返回一個str對象 把一個Python對象編碼轉換成Json字串

從python原始類型向json類型的轉化對照如下:

# json_dumps.pyimport jsonimport chardetlistStr = [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‘}
1.3、json.dump()

將Python內建類型序列化為json對象後寫入檔案

# json_dump.pyimport jsonlistStr = [{"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)
1.4、json.load()

讀取檔案中json形式的字串元素 轉化成python類型

# json_load.pyimport jsonstrList = 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‘}
 JsonPath

JsonPath 是一種資訊抽取類庫,是從JSON文檔中抽取指定資訊的工具,提供多種語言實現版本,包括:Javascript, Python, PHP 和 Java。

 

:https://pypi.python.org/pypi/jsonpath

安裝方法:點擊Download URL連結下載jsonpath,解壓之後執行python setup.py install

官方文檔:http://goessner.net/articles/JsonPath

JsonPath與XPath文法對比:

Json結構清晰,可讀性高,複雜度低,非常容易匹配,下表中對應了XPath的用法。

XPath JSONPath 描述
/ $ 根節點
. @ 現行節點
/ .or[] 取子節點
.. n/a 取父節點,Jsonpath未支援
// .. 就是不管位置,選擇所有合格條件
* * 匹配所有元素節點
@ n/a 根據屬性訪問,Json不支援,因為Json是個Key-value遞迴結構,不需要。
[] [] 迭代器標示(可以在裡邊做簡單的迭代操作,如數組下標,根據內容選值等)
| [,] 支援迭代器中做多選。
[] ?() 支援過濾操作.
n/a () 支援運算式計算
() n/a 分組,JsonPath不支援

JsonPath爬取拉勾網案例:

地址: http://www.lagou.com/lbs/getAllCitySearchLabels.json 

目標:擷取所有城市。

# jsonpath_lagou.pyimport urllib2import jsonpathimport jsonimport chardeturl = ‘http://www.lagou.com/lbs/getAllCitySearchLabels.json‘request =urllib2.Request(url)response = urllib2.urlopen(request)html = response.read()# 把json格式字串轉換成python對象jsonobj = json.loads(html)# 從根節點開始,匹配name節點citylist = jsonpath.jsonpath(jsonobj,‘$..name‘)print citylistprint type(citylist)fp = open(‘city.json‘,‘w‘)content = json.dumps(citylist, ensure_ascii=False)print contentfp.write(content.encode(‘utf-8‘))fp.close()
注意事項:

json.loads() 是把 Json格式字串解碼轉換成Python對象,如果在json.loads的時候出錯,要注意被解碼的Json字元的編碼。

如果傳入的字串的編碼不是UTF-8的話,需要指定字元編碼的參數 encoding

dataDict = json.loads(jsonStrGBK);

 

 

dataJsonStr是JSON字串,假設其編碼本身是非UTF-8的話而是GBK 的,那麼上述代碼會導致出錯,改為對應的:

  • dataDict = json.loads(jsonStrGBK, encoding="GBK");

 

如果 dataJsonStr通過encoding指定了合適的編碼,但其中又包含其他編碼的字元,則需要先將dataJsonStr轉換為Unicode,然後再指定編碼格式調用json.loads()

  • dataJsonStrUni = dataJsonStr.decode("GB2312"); dataDict = json.loads(dataJsonStrUni, encoding="GB2312");
##字串編碼轉換####任何平台的任何編碼 都能和 Unicode 互相轉換UTF-8 與 GBK 互相轉換,那就先把UTF-8轉換成Unicode,再從Unicode轉換成GBK,反之同理。``` python # 這是一個 UTF-8 編碼的字串utf8Str = "你好地球"# 1. 將 UTF-8 編碼的字串 轉換成 Unicode 編碼unicodeStr = utf8Str.decode("UTF-8")# 2. 再將 Unicode 編碼格式字串 轉換成 GBK 編碼gbkData = unicodeStr.encode("GBK")# 1. 再將 GBK 編碼格式字串 轉化成 UnicodeunicodeStr = gbkData.decode("gbk")# 2. 再將 Unicode 編碼格式字串轉換成 UTF-8utf8Str = unicodeStr.encode("UTF-8")

decode的作用是將其他編碼的字串轉換成 Unicode 編碼

encode的作用是將 Unicode 編碼轉換成其他編碼的字串

 

Python爬蟲開發【第1篇】【Json與JsonPath】

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.