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
이 연습은 강의의 일부입니다
Intermediate Importing Data in Python
연습 안내
- 관련 URL을 변수
url에 할당하세요. - 응답 객체
r에json()메서드를 적용하고, 결과 딕셔너리를 변수json_data에 저장하세요. - 변수
pizza_extract에는 Wikipedia의 Pizza 페이지에서 발췌한 HTML이 문자열로 들어 있어요.print()함수를 사용해 이 문자열을 셸에 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# 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']
____