반응형

🚀 Python으로 뉴스 자동 수집하여 FlexClip 영상 제작하는 완벽 가이드
💡 핵심 포인트: 이 가이드를 따라하면 30분 안에 뉴스를 자동으로 수집하고 FlexClip으로 영상을 자동 제작하는 시스템을 구축할 수 있습니다. 코딩 초보자도 쉽게 따라할 수 있도록 단계별로 상세히 설명드립니다!
Python을 활용한 뉴스 자동화 시스템 구축 이미지
🎯 Part 1: Python 뉴스 자동 수집 시스템 구축
1-1. 필요한 라이브러리 설치 및 환경 설정
첫 번째 단계: 뉴스 크롤링을 위한 필수 라이브러리들을 설치해야 합니다. 아래 명령어를 순서대로 실행하세요.
pip install requests beautifulsoup4 newspaper3k feedparser selenium webdriver-manager pandas openai
📚 라이브러리 설명:
- requests: 웹 페이지 요청을 위한 기본 라이브러리
- beautifulsoup4: HTML 파싱 및 데이터 추출용
- newspaper3k: 뉴스 기사 전문 크롤링 라이브러리
- feedparser: RSS 피드 처리용
- selenium: 동적 웹 페이지 크롤링用
- pandas: 데이터 정리 및 관리
- openai: GPT API를 통한 스크립트 생성
뉴스 자동 수집부터 영상 제작까지의 전체 프로세스
1-2. 뉴스 크롤링 핵심 코드 구현
두 번째 단계: 실제 뉴스를 수집하는 Python 코드를 작성합니다. 아래는 네이버 뉴스를 크롤링하는 기본 코드입니다.
import requests
from bs4 import BeautifulSoup
import pandas as pd
from datetime import datetime
import time
class NewsCollector:
def __init__(self):
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
self.news_data = []
def collect_naver_news(self, keyword, max_pages=3):
"""네이버 뉴스 수집 함수"""
for page in range(1, max_pages + 1):
url = f"https://search.naver.com/search.naver?where=news&query={keyword}&start={page*10-9}"
try:
response = requests.get(url, headers=self.headers)
soup = BeautifulSoup(response.text, 'html.parser')
articles = soup.find_all('div', class_='news_wrap')
for article in articles:
title = article.find('a', class_='news_tit')
summary = article.find('div', class_='news_dsc')
if title and summary:
news_item = {
'title': title.get_text().strip(),
'summary': summary.get_text().strip(),
'url': title.get('href'),
'collected_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
self.news_data.append(news_item)
time.sleep(1) # 서버 부하 방지
except Exception as e:
print(f"페이지 {page} 수집 중 오류: {e}")
return self.news_data
def save_to_csv(self, filename='news_data.csv'):
"""수집된 뉴스를 CSV로 저장"""
df = pd.DataFrame(self.news_data)
df.to_csv(filename, index=False, encoding='utf-8-sig')
print(f"뉴스 데이터가 {filename}에 저장되었습니다.")
# 사용 예시
collector = NewsCollector()
news_list = collector.collect_naver_news("인공지능", max_pages=5)
collector.save_to_csv("ai_news.csv")
| 뉴스 사이트 | 크롤링 난이도 | 데이터 품질 | 추천도 | 특징 |
|---|---|---|---|---|
| 네이버 뉴스 | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | 구조화된 데이터, 다양한 언론사 |
| 다음 뉴스 | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | 깔끔한 구조, 빠른 업데이트 |
| 구글 뉴스 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | 글로벌 뉴스, 다양한 언어 |
| RSS 피드 | ⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | 안정적, API 형태 제공 |
🎬 Part 2: GPT API를 활용한 스크립트 자동 생성
GPT API를 활용한 스크립트 자동 생성 과정
2-1. OpenAI API 설정 및 연동
🔑 API 키 발급 방법:
- OpenAI 공식 사이트에 회원가입
- API Keys 메뉴에서 새 API 키 생성
- 환경변수에 API 키 설정 (보안을 위해)
- 사용량 제한 및 결제 방법 설정
import openai
import os
from typing import List, Dict
class ScriptGenerator:
def __init__(self, api_key: str):
openai.api_key = api_key
self.client = openai.OpenAI(api_key=api_key)
def generate_video_script(self, news_data: List[Dict], video_length: int = 60) -> str:
"""뉴스 데이터를 바탕으로 영상 스크립트 생성"""
# 뉴스 요약 생성
news_summary = self.summarize_news(news_data)
prompt = f"""
다음 뉴스 정보들을 바탕으로 {video_length}초 분량의 유튜브 쇼츠 영상 스크립트를 작성해주세요.
뉴스 정보:
{news_summary}
스크립트 요구사항:
1. 시청자의 관심을 끄는 강력한 오프닝 (5초)
2. 핵심 내용 전달 (40초)
3. 마무리 및 구독 유도 (15초)
4. 각 구간별로 적절한 이미지나 영상 소스 제안
5. 자막으로 표시할 키워드 강조
출력 형식:
[0-5초] 오프닝: (대사)
- 추천 이미지: (설명)
[5-45초] 본문: (대사)
- 추천 이미지: (설명)
[45-60초] 마무리: (대사)
- 추천 이미지: (설명)
"""
try:
response = self.client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "당신은 전문적인 영상 스크립트 작가입니다."},
{"role": "user", "content": prompt}
],
max_tokens=1500,
temperature=0.7
)
return response.choices[0].message.content
except Exception as e:
print(f"스크립트 생성 중 오류 발생: {e}")
return None
def summarize_news(self, news_data: List[Dict]) -> str:
"""뉴스 데이터 요약"""
summaries = []
for news in news_data[:5]: # 상위 5개 뉴스만 사용
summaries.append(f"제목: {news['title']}\n요약: {news['summary']}")
return "\n\n".join(summaries)
# 사용 예시
api_key = "your-openai-api-key-here"
generator = ScriptGenerator(api_key)
# 앞서 수집한 뉴스 데이터 사용
script = generator.generate_video_script(news_list, video_length=60)
print(script)
2-2. 스크립트 최적화 및 개선
세 번째 단계: 생성된 스크립트를 FlexClip에 최적화된 형태로 변환하고 개선합니다.
| 스크립트 요소 | 중요도 | 최적화 포인트 | FlexClip 연동 팁 |
|---|---|---|---|
| 오프닝 훅 | ⭐⭐⭐⭐⭐ | 3초 내 관심 집중 | 임팩트 있는 이미지 + 굵은 자막 |
| 핵심 메시지 | ⭐⭐⭐⭐⭐ | 한 문장으로 요약 | 키워드 하이라이트 효과 |
| 시각적 요소 | ⭐⭐⭐⭐ | 텍스트와 이미지 조화 | 전환 효과 활용 |
| CTA (행동유도) | ⭐⭐⭐⭐ | 명확한 구독 유도 | 버튼 애니메이션 추가 |
60초 쇼츠 영상을 위한 최적 스크립트 구성
🎥 Part 3: FlexClip 연동 및 자동 영상 제작
FlexClip을 활용한 자동 영상 제작 과정
3-1. FlexClip API 연동 설정
🔧 FlexClip API 설정 가이드:
- FlexClip 공식 사이트에서 계정 생성
- API 액세스 권한 신청 (Business 플랜 이상 필요)
- API 키 및 토큰 발급받기
- API 문서 확인 및 테스트
import requests
import json
from typing import Dict, List
import time
class FlexClipAutomator:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api.flexclip.com/v1"
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def create_video_project(self, script_data: Dict) -> str:
"""새 영상 프로젝트 생성"""
project_data = {
"name": f"Auto News Video - {datetime.now().strftime('%Y%m%d_%H%M%S')}",
"template": "news_template",
"duration": 60,
"format": {
"width": 1080,
"height": 1920, # 세로형 쇼츠 형태
"fps": 30
}
}
try:
response = requests.post(
f"{self.base_url}/projects",
headers=self.headers,
json=project_data
)
if response.status_code == 201:
project_id = response.json()["project_id"]
print(f"프로젝트 생성 완료: {project_id}")
return project_id
else:
print(f"프로젝트 생성 실패: {response.text}")
return None
except Exception as e:
print(f"API 호출 오류: {e}")
return None
def add_text_scenes(self, project_id: str, script_segments: List[Dict]) -> bool:
"""스크립트 기반으로 텍스트 장면 추가"""
for i, segment in enumerate(script_segments):
scene_data = {
"type": "text",
"start_time": segment["start_time"],
"end_time": segment["end_time"],
"content": {
"text": segment["text"],
"font_size": 48,
"font_weight": "bold",
"color": "#FFFFFF",
"background_color": "rgba(0,0,0,0.7)",
"position": "center",
"animation": "fade_in"
}
}
try:
response = requests.post(
f"{self.base_url}/projects/{project_id}/scenes",
headers=self.headers,
json=scene_data
)
if response.status_code != 201:
print(f"장면 {i+1} 추가 실패: {response.text}")
return False
time.sleep(0.5) # API 제한 방지
except Exception as e:
print(f"장면 추가 중 오류: {e}")
return False
return True
def add_background_media(self, project_id: str, media_urls: List[str]) -> bool:
"""배경 이미지/영상 추가"""
for i, media_url in enumerate(media_urls):
media_data = {
"type": "background",
"source": media_url,
"start_time": i * 20, # 20초씩 배경 변경
"end_time": (i + 1) * 20,
"effects": {
"transition": "fade",
"zoom": "slow_zoom_in"
}
}
try:
response = requests.post(
f"{self.base_url}/projects/{project_id}/media",
headers=self.headers,
json=media_data
)
if response.status_code != 201:
print(f"미디어 {i+1} 추가 실패")
return False
except Exception as e:
print(f"미디어 추가 중 오류: {e}")
return False
return True
def render_video(self, project_id: str) -> str:
"""영상 렌더링 시작"""
render_settings = {
"quality": "1080p",
"format": "mp4",
"watermark": False
}
try:
response = requests.post(
f"{self.base_url}/projects/{project_id}/render",
headers=self.headers,
json=render_settings
)
if response.status_code == 202:
render_id = response.json()["render_id"]
print(f"렌더링 시작: {render_id}")
return render_id
else:
print(f"렌더링 시작 실패: {response.text}")
return None
except Exception as e:
print(f"렌더링 요청 오류: {e}")
return None
def check_render_status(self, render_id: str) -> Dict:
"""렌더링 상태 확인"""
try:
response = requests.get(
f"{self.base_url}/renders/{render_id}",
headers=self.headers
)
if response.status_code == 200:
return response.json()
else:
return {"status": "error", "message": response.text}
except Exception as e:
return {"status": "error", "message": str(e)}
# 통합 자동화 클래스
class NewsVideoAutomator:
def __init__(self, openai_key: str, flexclip_key: str):
self.news_collector = NewsCollector()
self.script_generator = ScriptGenerator(openai_key)
self.video_creator = FlexClipAutomator(flexclip_key)
def create_news_video(self, keyword: str, pages: int = 3) -> str:
"""전체 프로세스 실행"""
print("1. 뉴스 수집 중...")
news_data = self.news_collector.collect_naver_news(keyword, pages)
if not news_data:
print("뉴스 수집 실패")
return None
print(f"2. {len(news_data)}개 뉴스 수집 완료")
print("3. 스크립트 생성 중...")
script = self.script_generator.generate_video_script(news_data)
if not script:
print("스크립트 생성 실패")
return None
print("4. 영상 프로젝트 생성 중...")
project_id = self.video_creator.create_video_project({"script": script})
if not project_id:
print("프로젝트 생성 실패")
return None
print("5. 영상 렌더링 시작...")
render_id = self.video_creator.render_video(project_id)
if render_id:
print(f"✅ 모든 과정 완료! 렌더링 ID: {render_id}")
return render_id
else:
print("렌더링 시작 실패")
return None
# 사용 예시
automator = NewsVideoAutomator(
openai_key="your-openai-key",
flexclip_key="your-flexclip-key"
)
# 인공지능 관련 뉴스로 영상 자동 제작
result = automator.create_news_video("인공지능", pages=5)
3-2. 영상 품질 최적화 및 자동화 스케줄링
최종 단계: 정기적으로 뉴스를 수집하고 영상을 자동 제작하는 스케줄러를 설정합니다.
| 최적화 항목 | 설정값 | 효과 | 주의사항 |
|---|---|---|---|
| 영상 해상도 | 1080x1920 (9:16) | 모바일 최적화 | 쇼츠 규격 준수 |
| 프레임 레이트 | 30fps | 부드러운 재생 | 파일 크기 고려 |
| 비트레이트 | 5000kbps | 고품질 영상 | 업로드 시간 증가 |
| 오디오 품질 | 128kbps AAC | 명료한 음성 | TTS 품질 중요 |
import schedule
import time
from datetime import datetime
class NewsVideoScheduler:
def __init__(self, automator: NewsVideoAutomator):
self.automator = automator
self.keywords = ["인공지능", "블록체인", "메타버스", "NFT", "웹3.0"]
self.current_keyword_index = 0
def daily_video_creation(self):
"""매일 정해진 시간에 영상 생성"""
keyword = self.keywords[self.current_keyword_index]
print(f"\n=== {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===")
print(f"키워드 '{keyword}'로 영상 제작 시작")
try:
result = self.automator.create_news_video(keyword, pages=3)
if result:
print(f"✅ '{keyword}' 영상 제작 성공: {result}")
# 성공 로그 저장
with open("video_creation_log.txt", "a", encoding="utf-8") as f:
f.write(f"{datetime.now()}: SUCCESS - {keyword} - {result}\n")
else:
print(f"❌ '{keyword}' 영상 제작 실패")
# 실패 로그 저장
with open("video_creation_log.txt", "a", encoding="utf-8") as f:
f.write(f"{datetime.now()}: FAILED - {keyword}\n")
except Exception as e:
print(f"❌ 오류 발생: {e}")
with open("video_creation_log.txt", "a", encoding="utf-8") as f:
f.write(f"{datetime.now()}: ERROR - {keyword} - {str(e)}\n")
# 다음 키워드로 순환
self.current_keyword_index = (self.current_keyword_index + 1) % len(self.keywords)
def start_scheduler(self):
"""스케줄러 시작"""
# 매일 오전 9시에 영상 제작
schedule.every().day.at("09:00").do(self.daily_video_creation)
# 매일 오후 6시에도 영상 제작 (하루 2회)
schedule.every().day.at("18:00").do(self.daily_video_creation)
print("🚀 뉴스 영상 자동 제작 스케줄러 시작!")
print("매일 오전 9시, 오후 6시에 영상을 자동 제작합니다.")
while True:
schedule.run_pending()
time.sleep(60) # 1분마다 스케줄 체크
# 스케줄러 실행
automator = NewsVideoAutomator(
openai_key="your-openai-key",
flexclip_key="your-flexclip-key"
)
scheduler = NewsVideoScheduler(automator)
scheduler.start_scheduler()
💡 추가 최적화 팁:
- 키워드 다양화: 트렌딩 키워드를 실시간으로 수집하여 다양한 주제의 영상 제작
- 썸네일 자동 생성: DALL-E API를 활용한 맞춤형 썸네일 자동 생성
- A/B 테스트: 다양한 스크립트 스타일로 성과 비교 분석
- 실시간 모니터링: 영상 업로드 상태 및 성과 지표 자동 수집
완전 자동화된 뉴스 영상 제작 시스템 구조도
🎯 핵심 성공 포인트 요약
- 안정적인 크롤링: robots.txt 준수, 적절한 딜레이 설정으로 차단 방지
- 고품질 스크립트: GPT-4 활용으로 자연스럽고 매력적인 콘텐츠 생성
- 최적화된 영상: 모바일 우선 세로형 포맷, 명확한 자막과 시각 효과
- 지속적인 운영: 스케줄러를 통한 정기적 콘텐츠 생산
- 성과 분석: 로그 기록과 A/B 테스트로 지속적 개선
📚 추가 학습 자료
더 깊이 있는 학습을 원한다면 다음 공식 문서들을 참고하세요:
🔍 관련 핵심 키워드
Python 뉴스 크롤링, 자동 영상 제작, FlexClip API, GPT 스크립트 생성, 유튜브 쇼츠 자동화, 뉴스 영상 봇, 콘텐츠 자동화, 영상 편집 API, 인공지능 영상 제작, 뉴스 수집 자동화
반응형
LIST
'인공지능 AI' 카테고리의 다른 글
| 🚀 Copy.ai 완벽 가이드 2025: AI 콘텐츠 생성의 혁신적 솔루션 (0) | 2025.05.25 |
|---|---|
| 2025 AI 고객 지원: 40% 응답 시간 줄이는 3가지 챗봇 솔루션 (0) | 2025.05.25 |
| 2025 AI 콘텐츠 생성: 50% 제작 시간 단축하는 3가지 툴 (0) | 2025.05.25 |
| 🚀 뉴스 스크립트 자동화로 쇼츠 영상 제작하는 완벽 가이드 (0) | 2025.05.24 |
| 🤖 Python으로 뉴스 자동 수집하여 영상 제작하는 완벽 가이드 (0) | 2025.05.24 |
| 🎬 FlexClip AI 동영상 제작기 완벽 가이드 (0) | 2025.05.24 |
| Kapwing으로 고화질 비디오 제작하기 (0) | 2025.05.24 |
| 🎥 Pictory AI: 텍스트를 전문 동영상으로 자동 변환하는 혁신적 도구 (0) | 2025.05.24 |