URL만 주면 웹사이트를 읽고, GPT가 핵심만 마크다운으로 요약해 주는 미니 브라우저를 15분 안에 만들어 봅니다. Python 기초만 있으면 누구나 따라할 수 있도록 단계별로 설명했어요. 🚀
1. 개발 환경 & 사전 준비
- 파이썬 설치 (3.9 이상이면 OK)
- 가상 환경 (권장)
python -m venv venv && source venv/bin/activate
- 필요 패키지 설치
pip install requests beautifulsoup4 python-dotenv openai
.env 파일에
OPENAI_API_KEY=sk-proj-…
형태로 키를 저장하고 .gitignore
에 추가해 깃허브에 노출되지 않게 하세요.2. 웹페이지 크롤링 — Website
클래스
import requests
from bs4 import BeautifulSoup
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
class Website:
"""
주어진 URL을 다운로드해
- title : <title> 내용
- text : 본문에서 script/img/style 제거 후 순수 텍스트
를 보관하는 간단한 객체
"""
def __init__(self, url: str):
self.url = url
res = requests.get(url, headers=HEADERS, timeout=10)
soup = BeautifulSoup(res.content, "html.parser")
# 제목
self.title = soup.title.string.strip() if soup.title else "No title"
# 본문에서 불필요한 태그 제거
for bad in soup.body(["script", "style", "img", "input"]):
bad.decompose()
# 텍스트만 추출
self.text = soup.body.get_text("\n", strip=True)
3. GPT-4o에게 줄 “시스템 & 유저 프롬프트” 만들기
3-1. 시스템 프롬프트
system_prompt = (
"You are an assistant that analyzes the contents of a website "
"and provides a short summary, ignoring navigation text. "
"Respond in markdown."
)
3-2. 유저 프롬프트 함수
def user_prompt_for(site: Website) -> str:
prompt = f"You are looking at a website titled {site.title}.\n"
prompt += "The contents of this website is as follows; "
prompt += "please provide a short summary in markdown. "
prompt += "If it includes news or announcements, summarize those too.\n\n"
prompt += site.text
return prompt
3-3. 두 프롬프트를 합쳐서 messages
리스트 생성
def messages_for(site: Website):
return [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt_for(site)}
]
4. GPT-4o 호출 → 요약 결과 받기
from dotenv import load_dotenv
import os, openai
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY", "").strip()
if not api_key:
raise RuntimeError("OPENAI_API_KEY가 설정돼 있지 않아요!")
openai.api_key = api_key
def summarize(url: str) -> str:
"""
URL을 받아 Website 객체 생성 → GPT로 요약 → 요약 텍스트 반환
"""
site = Website(url)
response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=messages_for(site)
)
return response.choices[0].message.content
5. Jupyter Lab에서 마크다운 렌더링
노트북이라면 IPython.display.Markdown
을 이용하면 요약을 예쁘게 볼 수 있습니다.
from IPython.display import Markdown, display
def display_summary(url):
display(Markdown(summarize(url)))
display_summary("https://edwarddonner.com")
6. 확장 아이디어
- 언어 변경: 시스템 프롬프트 끝을
"Respond in markdown in Korean"
으로 바꿔 보세요. - 다중 URL 요약: 뉴스 포털 메인에서 링크를 모아 한꺼번에 실행.
- Flask / FastAPI로 감싸서 웹 서비스화.
- UI 추가: Streamlit으로 간단한 입력 폼 & 출력 카드 만들기.
주의: 사이트마다 robots.txt 정책이 다릅니다. 대량 크롤링 전에는 반드시 이용 약관을 확인하세요.
7. 마무리
이제 여러분은 requests + BeautifulSoup로 웹페이지를 파싱하고, GPT-4o와 대화형 프롬프트를 구성해 자동 요약을 얻는 전 과정을 경험했습니다. 여기에 캐싱, 예외 처리, 프록시 설정 등을 더하면 실전에서도 충분히 활용할 수 있는 작은 “AI 브라우저”가 완성됩니다. 즐거운 실험 되세요!