Lấy dữ liệu từ api bằng python

Bên cạnh thư viện BeautifulSoup đã giới thiệu, chúng ta có thể dùng các giao diện lập trình ứng dụng (Application Programming Interface) viết tắt là API được cung cấp bởi các website hay các dịch vụ web như Amazon, Facebook, Wikipedia, v.v. để hỗ trợ trong việc thu thập và trích xuất dữ liệu theo những định dạng có cấu trúc như XML hay JSON.

Để hiểu hơn về API và danh mục các API được cung cấp bởi các website, chúng ta tham khảo hai nguồn quan trọng sau:

  • https://www.programmableweb.com/api-university
  • https://www.pythonforbeginners.com/api/list-of-python-apis

Minh họa cách dùng API với GitHub

Hầu hết các websites sẽ yêu cầu chứng thực trước khi sử dụng các API của họ, nhưng có một số website cho phép sử dụng API mà không cần thông qua chứng thực, ví dụ GitHub. Tôi đã tạo một tài khoản trên GitHub là https://github.com/TranNgocMinh . Đoạn mã sau đây sẽ thu tập dữ liệu từ tài khoản này và hiển thị theo định dạng JSON:

import requests, json

acc_url = "https://api.github.com/users/TranNgocMinh"

acc_info = json.loads(requests.get(acc_url).text)

print(acc_info)

Dữ liệu thu thập được:

{'login': 'TranNgocMinh', 'id': 24805881, 'node_id': 'MDQ6VXNlcjI0ODA1ODgx', 
'avatar_url': 'https://avatars3.githubusercontent.com/u/24805881?v=4', 'gravatar_id': '', 
'url': 'https://api.github.com/users/TranNgocMinh', 
'html_url': 'https://github.com/TranNgocMinh', 
'followers_url': 'https://api.github.com/users/TranNgocMinh/followers', 
'following_url': 'https://api.github.com/users/TranNgocMinh/following{/other_user}', 
'gists_url': 'https://api.github.com/users/TranNgocMinh/gists{/gist_id}', 
'starred_url': 'https://api.github.com/users/TranNgocMinh/starred{/owner}{/repo}', 
'subscriptions_url': 'https://api.github.com/users/TranNgocMinh/subscriptions', 
'organizations_url': 'https://api.github.com/users/TranNgocMinh/orgs', 
'repos_url': 'https://api.github.com/users/TranNgocMinh/repos', 
'events_url': 'https://api.github.com/users/TranNgocMinh/events{/privacy}', 
'received_events_url': 'https://api.github.com/users/TranNgocMinh/received_events', 
'type': 'User', 'site_admin': False, 'name': 'Ngoc Minh', 'company': None, 
'blog': 'ngocminhtran.com', 'location': None, 'email': None, 'hireable': None, 
'bio': 'I am a teacher, a software developer. I love reading, programming, writing, 
travelling, so on.', 'public_repos': 25, 'public_gists': 36, 'followers': 12, 
'following': 0, 'created_at': '2016-12-28T07:52:04Z', 'updated_at': '2019-09-14T02:50:16Z'}

Từ dữ liệu trên, chúng ta có thể biết một vài thông tin cụ thể, ví dụ thời gian tạo tài khoản (created_at) hay thời gian cập nhật thông tin tài khoản mới nhất (updated_at):

'created_at': '2016-12-28T07:52:04Z'

'updated_at': '2019-09-14T02:50:16Z'

Trong ví dụ trên, created_at và updated_at là các key và chúng ta có thể lấy giá trị từ các key trong Python như sau:

print(acc_info['created_at'])

print(acc_info['updated_at'])

Thời gian chúng ta nhận được có thể được trích xuất theo ý muốn trong Python dùng hàm parse trong mô đun dateutil.parser. Nếu chưa có mô đun này, có thể cài đặt bằng lệnh:

pip instatll python-dateutil

Giả sử chúng ta muốn biết thông tin về tháng mà tôi tạo tài khoản GitHub, có thể viết:

import requests, json

from dateutil.parser import parse

acc_url = "https://api.github.com/users/TranNgocMinh"

acc_info = json.loads(requests.get(acc_url).text)

print(parse(acc_info['created_at']).month)

Kết quả: 12

Chúng ta có thể thể hiện thông tin về các public repository từ một tài khoản GitHub như đoạn mã sau:

import requests, json

repos_url = "https://api.github.com/users/TranNgocMinh/repos"

repos_info = json.loads(requests.get(repos_url).text)

print(repos_info)

Tài khoản GitHub của tôi trong thời điểm viết bài này có 25 repositories và chúng ta có thể biết tên tất cả các repositories này như sau:

repos_names = [repo["name"] for repo in repos_info]

print(repos_names)

Kết quả:

['andrew-ng-ml-solutions', 'ASP.NET-4.5', 'ASP.NET4.5Project', 'css-animation-101', 
'Data_Science_from_Scratch', 'javascript-algorithms', 'Kotlin-and-Android', 
'Learn-C-Sharp', 'Learn-Java', 'Machine-Learning', 'machinelearning', 
'My-solutions-for-ML-course-Andrew-Ng-', 'myBooks', 'My_Reading', 
'PythonDataScienceHandbook', 'Refactoring-Summary', 'SQLiteXamarinFormsDemo', 
'stanford-tensorflow-tutorials', 'stdlib', 'TensorFlow-Tutorials', 
'tensorflow_cookbook', 'the-book-of-secret-knowledge', 'Xamarin.Forms', 
'You-Dont-Know-JS', 'You-Dont-Need-jQuery']

Trên đây là ví dụ về việc chúng ta có thể tận dụng các API để thu thập dữ liệu dùng Python. Kế tiếp, chúng ta sẽ xem xét một ví dụ khác về cách dùng API của một trang web rất nổi tiếng là Wikipedia.

Minh họa cách dùng API từ trang Wikipedia

Một trong những cách nhanh nhất để dùng API của trang Wikipedia là truy cập trang https://www.pythonforbeginners.com/api/list-of-python-apis và tìm đến Wikipedia:

Lấy dữ liệu từ api bằng python

Nhấn vào dòng liên kết Api documentation để đến trang API của Wikipedia: https://www.mediawiki.org/wiki/API:Main_page

Nhấn vào dòng liên kết Python wrapper for Wikipedia để sử dụng thư viện API Python tên Wikipedia. Trang GitHub của thư viện này:

Lấy dữ liệu từ api bằng python

Để cài đặt thư viện này chúng ta dùng lệnh:

pip install wikipedia

Giả sử chúng ta muốn biết thông tin tiểu sử của Bill Gates, nếu tìm kiếm Google sẽ có hai phiên bản tiếng Việt và tiếng Anh:

Lấy dữ liệu từ api bằng python

Sử dụng ngôn ngữ mặc định là tiếng Anh, chúng ta có thể biết thông tin về Bill Gates dùng hàm summarycủa thư viện Wikipedia:

import wikipedia

print(wikipedia.summary("Bill Gates"))

Kết quả:

William Henry Gates III (born October 28, 1955) is an American business magnate, investor, 
author, philanthropist, and humanitarian. He is best known as the principal founder 
of Microsoft Corporation. During his career at Microsoft, Gates held the positions 
of chairman, CEO and chief software architect, while also being the largest 
individual shareholder until May 2014. Born and raised in Seattle, Washing…

Nếu muốn biết thông tin chỉ câu đầu tiên, có thể viết:

print(wikipedia.summary("Bill Gates",sentences=1))

Kết quả:

William Henry Gates III (born October 28, 1955) is an American business magnate, 
investor, author, philanthropist, and humanitarian.

Bây giờ, chúng ta muốn đọc thông tin Bill Gates bằng tiếng Việt, có thể dùng hàm set_lang từ thư viện Wikipedia:

import wikipedia

wikipedia.set_lang("vi")

print(wikipedia.summary("Bill Gates"))

Kết quả:

William Henry "Bill" Gates III (sinh ngày 28 tháng 10 năm 1955) là một doanh nhân người Mỹ, 
nhà từ thiện, tác giả và chủ tịch tập đoàn Microsoft, hãng phần mềm khổng lồ mà ông cùng 
với Paul Allen đã sáng lập ra. Ông luôn có mặt trong danh sách những người giàu nhất 
trên thế giới. và là người giàu nhất thế giới từ 1995 tới 2014, 
ngoại trừ tháng 3/2013, 3/2012, tháng 3/2011 (hạng 2) và 2008 khi ông chỉ xếp thứ ba. 
Tháng 5 năm 2013,…

Trên đây chỉ là ví dụ về cách dùng thư viện Wikipedia. Có thể tìm hiểu nhiều chức năng thú vị khác từ thư viện này tại https://github.com/goldsmith/Wikipedia

Lời kết

API là một trong những công cụ quan trọng nhất hỗ trợ chúng ta thu thập và trích xuất dữ liệu. Do đó, tìm hiểu và sử dụng thành thạo công cụ này là kĩ năng thiết yếu trong lĩnh vực machine learning.