안녕하세요? 좋은 주말이네요! ^-^
저번에 올려드린 그누보드 자동 글쓰기 함수를 활용하여
( https://sir.kr/g5_tip/15678 )
Youtube API의 비디오 50개 제한을 우회하면서 특정 채널의 영상을 퍼오는 Python 스크립트를 작성했어요~
[code]
import requests, pymysql, json
from tqdm import tqdm
from datetime import datetime
def board_write(board, subject, content, mb_id, nickname):
# MySQL connection 및 cursor 생성
conn = pymysql.connect(host = 'URL을입력하세요',
user = 'DB유저명을입력하세요',
password = 'DB비번을입력하세요',
db = 'DB명을입력하세요',
charset = 'utf8')
curs = conn.cursor()
# 작성글 INSERT
sql = f"select wr_num from g5_write_{board}"
curs.execute(sql)
wr_num = str(int(curs.fetchone()[0]) - 1)
now = datetime.today().strftime('%Y-%m-%d %H:%M:%S') # 그누보드의 날짜 형식 준수 (ex: 2021-04-05 23:45:15)
sql = f"insert into g5_write_{board} set wr_num = {wr_num}, \
wr_reply = '', wr_comment = 0, ca_name = '', wr_option = 'html1', wr_subject = '{subject}', \
wr_content = '{content}', wr_link1 = '', wr_link2 = '', \
wr_link1_hit = 0, wr_link2_hit = 0, wr_hit = 1, wr_good = 0, wr_nogood = 0, \
mb_id = '{mb_id}', wr_password = '', wr_name = '{nickname}', wr_email = '', wr_homepage = '', \
wr_datetime = '{now}', wr_last = '{now}', wr_ip = '111.111.111.111', \
wr_1 = '', wr_2 = '', wr_3 = '', wr_4 = '', wr_5 = '', \
wr_6 = '', wr_7 = '', wr_8 = '', wr_9 = '', wr_10 = '', \
wr_comment_reply = '', wr_facebook_user = '', wr_twitter_user = '', \
as_re_name = '', as_tag = '', as_map = '', as_icon = '', as_thumb = '', as_video = ''"
curs.execute(sql)
# 부모 아이디에 UPDATE
sql = f"select wr_id from g5_write_{board}"
curs.execute(sql)
wr_id = str(curs.fetchall()[-1][0])
sql = f"update g5_write_{board} set wr_parent = {wr_id} where wr_id = {wr_id}"
curs.execute(sql)
# 새글 INSERT
sql = f"insert into g5_board_new ( bo_table, wr_id, wr_parent, bn_datetime, mb_id ) values \
( '{board}', '{wr_id}', '{wr_id}', '{now}', '{mb_id}' )"
curs.execute(sql)
# 게시글 1 증가
sql = f"select bo_count_write from g5_board where bo_table = '{board}'"
curs.execute(sql)
bo_count_write = str(int(curs.fetchone()[0]))
sql = f"update g5_board set bo_count_write = {bo_count_write} + 1 where bo_table = '{board}'"
curs.execute(sql)
# MySQL connection 닫기
conn.close()
return
def get_all_video(c_id):
api_key = '유튜브API키를입력하세요'
base_search_url = 'https://www.googleapis.com/youtube/v3/search?'
start_url = base_search_url+'key={}&channelId={}&part=snippet,id&order=date&maxResults=25'.format(api_key, c_id)
video_data = dict()
url = start_url
while True:
resp = requests.get(url).text
data = json.loads(resp)
for i in data['items']:
if i['id']['kind'] == "youtube#video":
title = i['snippet']['title']
v_id = i['id']['videoId']
video_data[title] = v_id # key에 제목, value에 videoId를 넣습니다.
try:
next_page_token = data['nextPageToken']
url = start_url + '&pageToken={}'.format(next_page_token)
except:
break
return dict(reversed(list(video_data.items()))) # 역순이기 때문에 이를 뒤집어서 업로드 시간 순으로 정렬합니다.
channel_id = '채널ID를입력하세요'
result = get_all_video(channel_id)
board = '게시판명을입력하세요'
mb_id = 'ID를입력하세요'
nickname = '닉네임을입력하세요'
for key, value in tqdm(result.items()):
subject = key
content = f'<iframe width="560" height="315" src="https://www.youtube.com/embed/{value}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'
board_write(board, subject, content, mb_id, nickname)
[/code]
위 스크립트는 파이썬 3.7에서 테스트되었으며,
3.5 이하에서는 dictionary의 순서가 보존되지 않기 때문에 collections.OrderedDict를 사용하셔야 되어요~
참고로 파이썬 3.8에서는 보다 간단한 방법으로 reversed를 처리할 수 있습니다 :)
실행 결과는 다음과 같이 Progress bar로 표현했어요 ^^

Lancôme Korea 유튜브 채널에 들어가보면 현재 총 51개의 영상이 업로드되어 있는데,
그누보드(아미나)에 51개의 영상이 정상적으로 업로드된 결과를 캡쳐했어요 :)




게시글에 들어가보면 다음과 같이 업로드가 잘 되어있는 것을 확인할 수 있어요~ ^^

일반적으로 Youtube API는 최대 50개까지의 비디오에 대하여 데이터를 반환하지만,
위 스크립트에서는 nextPageToken을 이용하여 그 이상의 데이터도 받을 수 있도록 작성하였습니다!
다만 이 방식을 사용하더라도 구글 측에서 대략 500개 내외에서 제한을 거는 것 같네요 ㅠㅠ
그리고 위 스크립트에서 최종적으로 업로드한 videoId를 로그 파일에 저장하도록 하여 crontab에 넣으면
아미나의 'Basic Feed'와 유사한 용도로 활용할 수 있지만,
위 스크립트는 50개 이상의 데이터를 받아오도록 작성되었기 때문에
crontab으로 너무 자주 돌리면 Youtube API의 1일 최대 limit에 걸릴 수 있습니다 ㅠㅠ
다음에는 복수의 유튜브 채널에서 영상을 수집하여 crontab에 넣고 돌릴 수 있는 스크립트를 올려볼게요!
그럼 다들 즐겁고 뜻깊은 주말 오후 되시고, 일교차가 큰데 감기 조심하세요~ ^^
냑 회원님들께 항상 감사드립니다!
댓글 16개
게시글 목록
| 번호 | 제목 |
|---|---|
| 23606 | |
| 23598 | |
| 23585 | |
| 23579 | |
| 23578 | |
| 23564 | |
| 23550 | |
| 23549 | |
| 23548 | |
| 23529 | |
| 23510 | |
| 23507 | |
| 23481 | |
| 23471 | |
| 23453 | |
| 23452 | |
| 23450 | |
| 23436 | |
| 23428 | |
| 23404 | |
| 23396 | |
| 23389 | |
| 23380 | |
| 23369 | |
| 23350 | |
| 23337 | |
| 23317 | |
| 23307 | |
| 23298 | |
| 23290 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기