한 유튜브 계정은 여러 개의 채널을 관리할 수 있는데, 각각의 채널별 구독자 수를 가져와서 분석할 필요가 있을 수 있다. 이를 위해서 구글 스프레드시트의 A열에는 유튜브 채널 ID를 넣어놓고, 이들을 기반으로 그 오른쪽에 구독자 수를 자동으로 입력해주는 코드를 파이썬으로 만들어보았다.
import gspread
from datetime import datetime
import googleapiclient.discovery
from oauth2client.service_account import ServiceAccountCredentials
import time
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive',
]
json_file_name = 'your google spreadsheet auth file.json'
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file_name, scope)
gc = gspread.authorize(credentials)
spreadsheet_url = 'your google spreadsheet url'
api_service_name = "youtube"
api_version = "v3"
DEVELOPER_KEY="your youtube api key"
youtube = googleapiclient.discovery.build(
api_service_name, api_version, developerKey = DEVELOPER_KEY)
doc = gc.open_by_url(spreadsheet_url)
sheet=doc.worksheet('시트1')
for i in range(2,sheet.row_count+1):
ChID=sheet.cell(i,1).value
time.sleep(5)
request= youtube.channels().list(part="statistics",id=ChID)
print(int(dict(dict(dict(request.execute())["items"][0])["statistics"])["subscriberCount"]))
sheet.update_cell(i,4,int(dict(dict(dict(request.execute())["items"][0])["statistics"])["subscriberCount"]))