API抓取第三方資料

1-1、網絡爬蟲(web crawler)

如果想要抓天氣資訊,在Terminal里面執行:
gem install rest-client
成功會看到Successfully installed rest-client-2.0.1的信息。

接著開一個irb實驗看看,執行irb后,一行行輸入以下代碼:

require 'rest-client'
response = RestClient.get "http://www.weather.com.cn/weather1d/101010100.shtml"
response.body

資料顯示很亂,因為回傳的內容是HTML給瀏覽器顯示的,我們只看氣溫:

require 'nokogiri'
doc = Nokogiri::HTML.parse(response.body)
doc.css(".today .tem").map{ |x| x.text }  # 得到 ["\n13°C\n", "\n2°C\n", "\n"] 

透過Nokogiri這個庫我們解析HTML,透過CSS selector從文件中對比出想要的資訊。這就是網絡爬蟲(web crawler), 但這樣很辛苦,程式容易壞掉。所以用API存取資料。


1-2、什么是API?

API(Application Programming Interface)講的就是程序跟程序的接口,定義接口叫什么名字、要傳什么參數進去、它會回傳什么東西回來、可能會發生的錯誤等等。

在寫 Ruby 程序的時候,我們會呼叫庫(library)的方法,這時候 API 指的是方法(method)的名字、參數、回傳值等等,例如 Ruby Hash 的 API 文件
對 Web 應用來說,客戶端和服務器之間是用 HTTP 通訊協定:抓資料的一方叫做 Client 客戶端,送出 HTTP request,在之前的課程中,這個角色就是瀏覽器,在這堂課中,我們會自己撰寫 Ruby 程序作為客戶端。回傳資料的一方叫做 server 服務端,回傳 HTTP response,服務端例如我們已經學過的 Ruby on Rails。

Web 應用的 API 就是在定義網址 URL 長怎樣、請求的 HTTP 方法(GET或POST等)是什么、要傳什么參數過去、返回的資料格式又是什么。這份教材要示范的,就是屬于這一種 API。
其中返回格式最常用的是 JSON 或 XML。這兩種是最常見的資料交換格式,專門用來讓機器之間交換資料用的,只有純粹的資料,不像 HTML 有沒有雜七雜八的排版資訊。一個 JSON 字串例如:
{ "id": 123, "name": "foobar"}

就是在描述一個哈希,不同程式語言都可以產生和解析這一個字串,讓我們在 irb
中實驗看看,我們可以把任意的 Ruby 資料,轉成 JSON 字串:
require 'json'{ :id => 123, :name => "foobar" }.to_json # => "{\"id\":123,\"name\":\"foobar\"}"

你可以再開另一個 Terminal,再進入 irb
,把剛剛的 JSON 字串貼上來
require 'json'JSON.parse( "{\"id\":123,\"name\":\"foobar\"}" ) # => {"id"=>123, "name"=>"foobar"}

這樣就又把 JSON 字串又轉回 Ruby 了。
所以如果能有 Web API 提供 JSON 資料的話,就可以透過程式語言直接解析拿到純粹的資料,非常方便又可靠。


1-3、注冊聚合數據,拿到API Key

讓我們找找看有沒有提供天氣 API 的服務商,找到了由聚合數據提供的 全國天氣預報 API,請先注冊,然后申請天氣預報數據:

然后就可以拿到 API Key,請記下這個憑證,等會呼叫 API 時會用到:

API 服務商都會要求你先注冊,然后呼叫 API 時需要帶著這個 API Key 參數,用來記錄呼叫者和使用次數。

1-4、安裝Postman進行初步測試

要怎么對 Web API 進行手動的測試呢? 我們來裝一個 Chrome Extension 叫做 Postman,這就是一個萬用的表單工具。
首先進入 Chrome 選單上的 Windows > Extensions,然后安裝 Postman

透過這個工具,我們可以指定 URL 地址、HTTP 方法和要傳遞的參數。讓我們實驗看。根據 全國天氣預報 文檔 的說明,讓我們試試看來抓「支持城市列表」

在 Postman 中輸入接口的 URL 地址和參數:

點擊 Send 就可以看到結果了:

1-5、用rest-client抓下來看

接下來實驗 Ruby 客戶端,用 Ruby 程序來抓取上述的資料。
進入 irb

require 'rest-client'require 'json'response = RestClient.get "http://v.juhe.cn/weather/citys", :params => { :key => "請換成你的Key" } data = JSON.parse(response.body)

這個 data 變量就是單純的 Ruby 哈希資料了,是全部的城市。接下來我們可以觀察一下這個資料的樣子,文檔上面也有范例:
data.keys # => ["resultcode", "reason", "result", "error_code"]data["result"][0] # => {"id"=>"1", "province"=>"北京", "city"=>"北京", "district"=>"北京"}

2-2初始專案,建立City Model

在 Terminal 下輸入:

 rails new api_exercise
 cd api_exercise
 git init 

編輯 Gemfile 加上gem 'rest-client',然后執行 bundle

執行 rails g model city

編輯 city 的 migration 檔案 db/migrate/201703XXXXXXXX_create_cities.rb

 class CreateCities < ActiveRecord::Migration[5.0]
   def change
     create_table :cities do |t|
+      t.string :juhe_id
+      t.string :province
+      t.string :city
+      t.string :district
+      t.string :current_temp
       t.timestamps
     end
+    add_index :cities, :juhe_id
   end
 end

然后rake db:migrate

2-3 抓取區城市資料儲存下來

新增 lib/tasks/dev.rake,放在這個目錄下的 rake 檔案是用來編寫任務腳本,讓我們在 Terminal 中可以執行它:

lib/tasks/dev.rake

namespace :dev do
  task :fetch_city => :environment do
    puts "Fetch city data..."
    response = RestClient.get "http://v.juhe.cn/weather/citys", :params => { :key => "你申請的key放這里" }
    data = JSON.parse(response.body)
    data["result"].each do |c|
      existing_city = City.find_by_juhe_id( c["id"] )
      if existing_city.nil?
        City.create!( :juhe_id => c["id"], :province => c["province"],
                      :city => c["city"], :district => c["district"] )
      end
    end
    puts "Total: #{City.count} cities"
  end
end

執行 bundle exec rake dev:fetch_city就會執行這個任務,把 2574 筆城市存進數據庫。

juhe_id 這個欄位的目的是存下第三方那邊的 id,這樣我們之后在更新數據的時候,就可以進行比對、避免重復新增。


2-4 在畫面顯示出來

編輯 config/routes.rb
新增一行 ·resources :cities·

config/routes.rb

Rails.application.routes.draw do+ resources :cities end 

執行rails g controller cities

編輯 app/controllers/cities_controller.rb

app/controllers/cities_controller.rb

class CitiesController < ApplicationController
+ def index
+ @cities = City.all
+ end 
end

新增 app/views/cities/index.html.erb

app/views/cities/index.html.erb

<table class="table">
<tr>
  <th>Juhe ID</th>
  <th>Province</th>
  <th>City</th>
  <th>District</th>
  <th>Temp</th>
</tr>
<% @cities.each do |city| %>
  <tr>
    <td><%= city.juhe_id %></td>
    <td><%= city.province %></td>
    <td><%= city.city %></td>
    <td><%= city.district %></td>
    <td></td>
  </tr>
<% end %>
</table>

啟動服務器rails s
,打開瀏覽器 http://localhost:3000/cities
就會看到城市資料了。

這里省略了安裝 Bootstrap 的步驟,如果沒安裝也沒關系,畫面會有差異而已。

2-5 更新城市天氣

我們希望存下來當前溫度。根據 文檔 的說明,可以找到氣溫的 API 說明。
首先修改 config/routes.rb
,新增一個操作:

config/routes.rb
- resources :cities+ resources :cities do+ member do+ post :update_temp+ end+ end

在畫面上放一個按鈕,編輯 app/views/cities/index.html.erb

- <td></td>
+ <td>
+   <%= city.current_temp %>
+   <%= link_to "更新溫度", update_temp_city_path(city), :method => :post %>
+ </td>

新增一個 action,編輯 app/controller/cities_controller.rb

def update_temp
    city = City.find(params[:id])
    response = RestClient.get "http://v.juhe.cn/weather/index", 
                              :params => { :cityname => city.juhe_id, :key => "你申請的key放這里" }
    data = JSON.parse(response.body)
    city.update( :current_temp => data["result"]["sk"]["temp"] )
    redirect_to cities_path
end

這樣點擊「更新溫度」后,就會更新氣溫了。

2-6保護API Key

在串接第三方應用時,第三方的 API Key 我們不希望寫死在程式碼里面,一來是因為我們不想把這些敏感的 keys 放到版本控制系統里面。二來是因為將來布署的時候,在 production 環境下,api key 會另外申請一個不一樣,因此我們希望容易抽換。

新增 config/juhe.yml 作為設定檔,內容如下:

 development:
  api_key: "你申請的key放這里"
production:
  api_key: "之后布署上production的話,key放這里"

編輯 config/application.rb,在最下面插入一行:

# (略)
JUHE_CONFIG = Rails.application.config_for(:juhe)

編輯 app/controller/cities_controller.rblib/tasks/dev.rake,把 "你申請的key放這里" 置換成 JUHE_CONFIG["api_key"] 即可。

(以上操作完成后要重啟rails s才會生效)

要注意:

  • YAML 格式使用空白縮排來表達資料的階層關系,請務必縮排整齊
  • YAML 格式會區分數字和字串,例如 01234 會看成 1234,如果要確保被解析成字串,請加上引號,例如"01234"
  • 讀出來的 Hash 是用字串 key,不是 symbol key。是 JUHE_CONFIG["api_key"]而不是 JUHE_CONFIG[:api_key]
    接著我們要告訴 Git 不要 commit 這個檔案,這樣就不用擔心 git push 會把 api key 洩漏出去。

編輯.gitignore,插入一行

config/juhe.yml

依照慣例,你可以復制一個 juhe.yml.example 檔案放進版本控制系統里面,這可以給你同事當作范例參考,內容例如:

config/juhe.yml.example

development:
  api_key: "<juhe api key>"

一些數據網站:
https://www.juhe.cn
http://apistore.baidu.com
https://www.haoduoshuju.com
http://www.pm25.in/api_doc
https://github.com/toddmotto/public-apis
http://opendatachina.com/en/projects/
END

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容