코딩응급실
[Python] URL로 가사 긁어와서 ppt에 자동으로 가사 붙여넣기 본문
필요한 파이썬 라이브러리 설치
pip install python-pptx beautifulsoup4 requests
파이썬 코드
from pptx import Presentation
from pptx.util import Pt
import requests
from bs4 import BeautifulSoup
# 1. Bugs에서 가사 가져오기
def get_lyrics_from_bugs(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Bugs 가사 태그를 찾음 (필요 시 URL에 맞게 태그 확인)
lyrics_tag = soup.find('div', class_='lyricsContainer')
if not lyrics_tag:
raise Exception("가사를 찾을 수 없습니다. URL을 확인하세요.")
lyrics = lyrics_tag.get_text(strip=True).split('\n') # 줄바꿈으로 분리
return lyrics
# 2. song.ppt 템플릿 수정
def create_ppt_with_lyrics(lyrics, template_path, output_path):
prs = Presentation(template_path)
slide_layout = prs.slide_layouts[0] # 템플릿 레이아웃 선택
for i in range(0, len(lyrics), 2): # 2줄씩 슬라이드 생성
slide = prs.slides.add_slide(slide_layout)
title = slide.shapes.title
content = slide.placeholders[1]
# 텍스트 설정
title.text = "가사 슬라이드"
text = "\n".join(lyrics[i:i + 2]) # 2줄 묶음
content.text = text
# 글꼴 크기 조정 (옵션)
for paragraph in content.text_frame.paragraphs:
for run in paragraph.runs:
run.font.size = Pt(24)
prs.save(output_path)
print(f"PPT가 {output_path}에 저장되었습니다.")
# 3. 실행
if __name__ == "__main__":
bugs_url = input("Bugs 가사 URL을 입력하세요: ")
lyrics = get_lyrics_from_bugs(bugs_url)
template = "song.ppt" # 이미 만들어둔 템플릿 파일 경로
output = "output_song.ppt" # 저장될 결과 파일 이름
create_ppt_with_lyrics(lyrics, template, output)
사용 방법
1. Bugs에서 노래 가사가 있는 페이지의 URL을 복사하여 입력합니다.
2. 템플릿 파일 song.ppt와 같은 경로에 저장합니다.
3. 스크립트를 실행하면 output_song.ppt라는 파일이 생성됩니다.
주의사항
Bugs 사이트의 HTML 구조는 변동될 수 있으므로, 크롤링 태그를 확인해야 합니다.
템플릿에는 반드시 가사가 들어갈 공간(플레이스홀더)이 있어야 합니다.
HTML 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PPT Lyrics Generator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Lyrics to PPT Generator</h1>
<form id="lyricsForm">
<label for="bugsUrl">Enter Bugs Lyrics URL:</label>
<input type="url" id="bugsUrl" placeholder="https://music.bugs.co.kr/track/..." required>
<button type="submit">Generate PPT</button>
</form>
<div id="status"></div>
</div>
<script src="libraries/pptxgen.min.js"></script> <!-- PPT 라이브러리 -->
<script src="script.js"></script>
</body>
</html>
CSS 코드
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
color: #333;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
width: 300px;
}
h1 {
font-size: 20px;
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
}
input {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
width: 100%;
padding: 10px;
border: none;
background-color: #007bff;
color: white;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
#status {
margin-top: 10px;
font-size: 14px;
color: green;
}
JS 코드
document.getElementById("lyricsForm").addEventListener("submit", async (e) => {
e.preventDefault();
const bugsUrl = document.getElementById("bugsUrl").value;
const statusDiv = document.getElementById("status");
statusDiv.textContent = "Fetching lyrics...";
try {
// 1. Bugs 가사 크롤링 (프록시 서버 필요 시 대체)
const lyrics = await fetchLyricsFromBugs(bugsUrl);
statusDiv.textContent = "Lyrics fetched successfully! Generating PPT...";
// 2. PPT 생성
createPpt(lyrics);
statusDiv.textContent = "PPT generated! Check your downloads.";
} catch (error) {
statusDiv.textContent = `Error: ${error.message}`;
}
});
async function fetchLyricsFromBugs(url) {
const response = await fetch(url);
const text = await response.text();
// Bugs HTML 구조에서 가사 추출
const parser = new DOMParser();
const doc = parser.parseFromString(text, "text/html");
const lyricsContainer = doc.querySelector(".lyricsContainer");
if (!lyricsContainer) throw new Error("Lyrics not found on the page.");
// 가사 텍스트 분리 및 반환
return lyricsContainer.innerText.split("\n").filter((line) => line.trim());
}
function createPpt(lyrics) {
const ppt = new PptxGenJS();
// 2줄씩 슬라이드에 추가
for (let i = 0; i < lyrics.length; i += 2) {
const slide = ppt.addSlide();
slide.addText(lyrics.slice(i, i + 2).join("\n"), {
x: 1, y: 1, w: 8, h: 5,
fontSize: 24, color: "363636", align: "center",
});
}
// PPT 저장
ppt.writeFile("Lyrics_PPT");
}
PPT 라이브러리 추가
PptxGenJS 라이브러리를 다운로드하여 /libraries 폴더에 추가합니다.
실행 방법
1. 위 코드를 파일로 저장 후 브라우저에서 index.html 열기.
2. Bugs URL 입력 → PPT 자동 생성 및 다운로드.
주의 사항
Bugs 사이트가 크로스 도메인 보안을 설정했다면, CORS 프록시를 사용해야 합니다.
예: fetch("https://cors-anywhere.herokuapp.com/" + url)
Bugs HTML 구조가 변경되면 lyricsContainer 클래스를 업데이트해야 합니다.
'Python' 카테고리의 다른 글
[Python] 네이버 리뷰(닉네임, 사진url, 내용 등) 크롤링하기 with. selenium (4) | 2024.10.24 |
---|---|
프로그래머스: 자릿수 더하기 (0) | 2024.10.15 |
프로그래머스: 짝수와 홀수 (1) | 2024.10.14 |
프로그래머스: x만큼 간격이 있는 n개의 숫자 (0) | 2024.10.14 |
프로그래머스: 평균 구하기 (0) | 2024.10.14 |