728x90
유튜브 API를 사용하여 원하는 검색 결과에 따른 결과를 json 형태로 반환해주는 프로그램을 만들어보겠습니다. 최종적으로 ngrok을 사용하여 API 요청이 가능하게 만들겠습니다. 자세한 사항은 유튜브 문서에서 확인 가능합니다.
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from oauth2client.tools import argparser
검색에 필요한 패키지를 가져와줍니다.
def build_youtube_search(developer_key):
DEVELOPER_KEY = developer_key
YOUTUBE_API_SERVICE_NAME="youtube"
YOUTUBE_API_VERSION="v3"
return build(YOUTUBE_API_SERVICE_NAME,YOUTUBE_API_VERSION,developerKey=DEVELOPER_KEY)
위 함수에서 developer_key는 자신의 API KEY를 사용하시면 됩니다. 추후 url로 요청을 보내기 위하여 인자로 받게 설정하였습니다.
def get_search_response(youtube, query):
search_response = youtube.search().list(
q = query,
order = "relevance",
part = "snippet",
maxResults = 10
).execute()
return search_response
- q: 검색하고자 하는 검색어를 지정하면 됩니다.
- order: 정렬 방법 date, rating, relevance 등이 있습니다.
- part: 필수 매개변수로 반환되는 결과의 구조를 결정합니다.
- maxResults: 최대 검색 결과 개수입니다.
def get_video_info(search_response):
result_json = {}
idx =0
for item in search_response['items']:
if item['id']['kind'] == 'youtube#video':
result_json[idx] = info_to_dict(item['id']['videoId'], item['snippet']['title'], item['snippet']['description'], item['snippet']['thumbnails']['medium']['url'])
idx += 1
return result_json
가져온 결과들을 원하는 정보만 모아서 딕셔너리 안에 딕셔너리 형태로 만들어서 결과로 반환해줍니다. 이때 playlist 타입은 원하는 정보가 아닐 확률이 커서 video 타입만 결과에 넣어주었습니다.
def info_to_dict(videoId, title, description, url):
result = {
"videoId": videoId,
"title": title,
"description": description,
"url": url
}
return result
videoId, title, description, url 정보를 받아서 딕셔너리 형태로 반환해줍니다.
728x90
'Python' 카테고리의 다른 글
[Python] 데코레이터가 뭐야? (0) | 2021.08.02 |
---|---|
[python] 유튜브 API를 사용하여 검색 결과 가져오기 (2) (0) | 2021.06.07 |
[Python] 네이버 영화 리뷰 데이터 수집 (2) (0) | 2021.05.18 |
[python] wordcloud를 사용한 네이버 영화 리뷰 시각화 (0) | 2021.04.09 |
[Python] 네이버 영화 리뷰 데이터 수집 (1) (0) | 2021.04.07 |