Scrapy:抓取返回數據格式爲JSON的網站內容

有些網站的數據是通過ajax請求獲取的,或者提供了json格式的api。

比如對於如下的數據:

[javascript] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. {  
  2.         {  
  3.             "url""http://www.techbrood.com/news/1",  
  4.             "author""iefreer",  
  5.             "title""techbrood Co. test 1"  
  6.         },  
  7.         {  
  8.             "url""http://www.techbrood.com/news/2",  
  9.             "author""ryan.chen",  
  10.             "title""techbrood Co. test 2"  
  11.         }  
  12. }  

在Scrapy裏,只要簡單改寫下parse函數就行:

[python] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. def parse(self, response):  
  2.     sites = json.loads(response.body_as_unicode())  
  3.     for site in sites:  
  4.         print site['url']  


調用body_as_unicode()是爲了能處理unicode編碼的數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章