TL;DR
웹페이지 전체 HTML을 LLM에 전달하면 script, navigation, footer, popup과 반복 문구가 입력에 섞여 토큰과 처리 부담이 커집니다. 이 튜토리얼은 Python에서 requests로 HTML을 가져오고 BeautifulSoup으로 잡음을 제거한 뒤 markdownify로 Markdown을 만들며, gpt-5.4-nano가 사용자 질문에 필요한 답변만 생성하도록 연결합니다. prompt에는 페이지에 있는 정보만 사용하고 없는 내용은 만들지 말라는 제약을 넣어 Olostep 홈페이지와 pricing 페이지의 질문 응답을 테스트합니다. 결과는 Markdown으로 화면에 표시하거나 파일로 저장할 수 있지만, 서버 운영과 API 호출, 페이지 변경 대응 비용까지 고려하면 기존 scraping API와 직접 구축 방식을 비교해야 합니다.
섹션별 상세
def clean_html(html):
html = fix_text(html)
soup = BeautifulSoup(html, "html.parser")
# Remove obvious noisy tags
for tag in soup([
"script", "style", "noscript", "svg", "img", "iframe", "nav", "header", "footer", "aside", "form", "button"
]):
tag.decompose()
noise_words = [
"cursor", "modal", "popup", "floating", "signup", "login", "cookie", "banner", "navbar", "menu", "footer", "header", "subscribe", "newsletter", "loading", "wait", "success", "auth", "w-nav", "w-form"
]
# First collect noisy tags
tags_to_remove = []
for tag in soup.find_all(True):
if tag.attrs is None:
continue
class_value = tag.get("class", [])
id_value = tag.get("id", "")
if isinstance(class_value, list):
class_text = " ".join(class_value).lower()
else:
class_text = str(class_value).lower()
id_text = str(id_value).lower()
if any(word in class_text or word in id_text for word in noise_words):
tags_to_remove.append(tag)
# Then remove them safely
for tag in tags_to_remove:
tag.decompose()
body = soup.body if soup.body else soup
return str(body)문자열 인코딩을 보정한 뒤 불필요한 HTML 태그와 class·id 기반 잡음 요소를 제거합니다.

def html_to_markdown(html):
markdown_text = markdownify_html(
html,
heading_style="ATX",
bullets="-"
)
markdown_text = fix_text(markdown_text)
# Remove image markdown
markdown_text = re.sub(r"!\[.*?\]\(.*?\)", "", markdown_text)
# Remove extra spaces and blank lines
markdown_text = re.sub(r"[ \t]+", " ", markdown_text)
markdown_text = re.sub(r"
{3,}", "
", markdown_text)
lines = []
skip_lines = [
"click to try", "wait...", "you've successfully reserved your spot.", "thank you! your submission has been received!", "oops! something went wrong while submitting the form.", "product", "resources", "company"
]
for line in markdown_text.splitlines():
line = line.strip()
if not line: continue
if line.lower() in skip_lines: continue
lines.append(line)
return "
".join(lines)정제된 HTML을 읽기 쉬운 Markdown으로 바꾸고 이미지 링크, 과도한 공백, 반복된 문구를 제거합니다.

def answer_query_from_page(markdown_text, user_query):
prompt = f"""
You are an AI web scraping assistant. You will receive Markdown extracted from a webpage. Your task is to answer the user's query using only the useful page content.
User query: {user_query}
Webpage Markdown: {markdown_text}
Instructions:
- Return only clean Markdown.
- Use only information from the webpage Markdown.
- Do not invent missing details.
- Ignore navigation links, buttons, CTAs, popups, decorative labels, image captions, and repeated marketing fragments.
- Ignore lines like "Start for free", "Contact Sales", "Your AI Agent", and decorative workflow examples unless they directly answer the query.
- Focus on headings, paragraphs, product descriptions, feature sections, pricing details, documentation text, and factual claims.
- If the page does not contain the answer, say: "The page does not contain this information."
- Keep the answer short, clear, and focused.
"""
response = client.responses.create(
model=MODEL_NAME,
input=prompt
)
return response.output_text사용자 질문과 웹페이지 Markdown을 LLM에 전달하고 페이지에 있는 정보만 사용한 짧은 Markdown 답변을 반환합니다.
def ai_web_scraper(url, user_query):
raw_html = fetch_page(url)
cleaned_html = clean_html(raw_html)
markdown_text = html_to_markdown(cleaned_html)
answer = answer_query_from_page(markdown_text, user_query)
return answer웹페이지 수집, HTML 정제, Markdown 변환, 질문 응답을 하나의 재사용 가능한 함수로 연결합니다.



용어 해설
- 웹 스크래핑(Web Scraping)
- — 웹 스크래핑은 웹사이트에서 정보를 자동으로 수집하는 기술입니다. requests로 페이지 HTML을 가져온 뒤 BeautifulSoup으로 구조를 파싱하고 불필요한 요소를 제거해 필요한 콘텐츠만 남깁니다. LLM 애플리케이션에서는 입력 토큰과 잡음을 줄이는 전처리 단계로 중요합니다.
- Markdown
- — Markdown은 제목, 문단, 목록 같은 구조를 간결한 텍스트 문법으로 표현하는 형식입니다. 이 글에서는 정제된 HTML을 Markdown으로 변환해 이미지와 반복된 레이아웃을 제거하고, LLM이 읽기 쉬운 입력으로 만듭니다. 최종 답변 저장과 후속 workflow 연결에도 활용됩니다.
- 대규모 언어 모델(Large Language Model)
- — 대규모 언어 모델은 텍스트를 입력받아 문맥을 파악하고 자연어 결과를 생성하는 모델입니다. 이 파이프라인에서는 정제된 웹페이지 Markdown과 사용자의 질문을 함께 받아 페이지에 근거한 짧은 답변을 생성합니다. 원문에 없는 정보의 추측을 막도록 입력 범위와 출력 형식을 prompt에서 제한합니다.
- HTML 파서(HTML Parser)
- — HTML 파서는 웹 문서를 태그와 속성으로 분해해 프로그램이 다룰 수 있는 구조로 바꾸는 도구입니다. BeautifulSoup은 이를 이용해 script, style, nav, footer 같은 태그를 찾아 삭제하고 class와 id에 포함된 잡음 단어도 검사합니다. 결과적으로 LLM에 전달할 본문 중심의 HTML이 남습니다.
기술
- Python
- Jupyter Notebook
- requests
- BeautifulSoup
- markdownify
- OpenAI
- ftfy
- python-dotenv
- gpt-5.4-nano
- Markdown
- HTML
활용 사례
- 특정 웹페이지에서 회사 개요를 추출하는 질의응답 도구
- pricing 페이지에서 가격 정보를 찾아 Markdown으로 정리하는 workflow
- 정제된 웹 콘텐츠를 chatbot이나 AI agent에 전달하는 파이프라인
- 웹페이지 답변을 Markdown 파일로 저장해 후속 작업에 활용하는 자동화
언급된 리소스
AI 요약 · 북마크 · 개인 피드 설정 — 무료
출처 · 인용 안내
인용 시 "요약 출처: AI Trends (aitrends.kr)"를 표기하고, 사실 확인은 원문 보기 기준으로 진행해 주세요. 자세한 기준은 운영 정책을 참고해 주세요.

