開始使用免費開始

試用 Wikipedia API

你目前表現很棒、學得也很開心,所以我們再帶你試試另一個 API:Wikipedia API(文件在這裡)。你將學會如何從 Wikipedia 上的「Pizza」頁面找到並擷取資訊。比較特別的是,你的查詢會回傳「巢狀」JSON,也就是 JSON 裡面再包 JSON。Python 可以處理這種情況,因為它會把結果轉換成「字典中的字典」。

向 Wikipedia API 請求此查詢的 URL 為:

https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=pizza

本練習屬於課程

Python 資料匯入進階

檢視課程

練習說明

  • 將相關的 URL 指派給變數 url
  • 對回應物件 r 套用 json() 方法,並將得到的字典存入變數 json_data
  • 變數 pizza_extract 以字串形式保存了 Wikipedia「Pizza」頁面部分內容的 HTML;使用 print() 函式在 Shell 中列印此字串。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import package
import requests

# Assign URL to variable: url


# Always include a descriptive User-Agent (Wikipedia requires this)
headers = {
    "User-Agent": "Checking out the Wikipedia API"
}

# Package the request, send the request and catch the response: r
r = requests.get(url, headers=headers)

# Decode the JSON data into a dictionary: json_data


# Print the Wikipedia page extract
pizza_extract = json_data['query']['pages']['24768']['extract']
____
編輯並執行程式碼