import requests
import random
import time
import logging
from bs4 import BeautifulSoup
import gradio as gr
from urllib.parse import urlparse, urlunparse
"""
[기본사항]
# 한국어로 설명
# 허깅페이스의 그라디오 환경에서 동작되는 스페이스
# 요청한 사항의 코드를 임의적으로 축소/삭제하지 말고 전체코드를 출력
[요청사항]
1) 네이버 블로그 링크를 입력하면, 해당 링크의 제목과 본문 내용을 스크래핑
2) 출력은 제목과 본문내용이 텍스트창에 한 번에 나오도록
3) 타겟 URL 예시:
- 기본: https://blog.naver.com/acoloje/223783254325
4) 데이터 HTML 구조(제목):
5) 데이터HTML 구조(본문):
[차단방지 적용자료]
1. Header 설정하기 (User-Agent, Referer 등)
2. User-Agent 랜덤 설정
3. Referer 설정 (네이버 모바일 페이지에서 온 것처럼 보이도록)
4. 랜덤 딜레이 (1~3초)
"""
# 디버깅 로그 설정 (UI에는 보이지 않고 debug.log 파일에 기록)
logging.basicConfig(
filename='debug.log',
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.debug("애플리케이션 시작.")
# 여러 브라우저의 User-Agent 문자열 리스트
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:115.0) Gecko/20100101 Firefox/115.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15",
]
def get_random_user_agent():
user_agent = random.choice(USER_AGENTS)
logging.debug(f"선택된 User-Agent: {user_agent}")
return user_agent
def convert_to_mobile_url(url):
"""
PC 버전 blog.naver.com 주소를 m.blog.naver.com으로 변환하여
모바일 페이지를 요청할 수 있도록 함.
"""
parsed = urlparse(url)
if "blog.naver.com" in parsed.netloc and "m.blog.naver.com" not in parsed.netloc:
new_netloc = parsed.netloc.replace("blog.naver.com", "m.blog.naver.com")
new_url = urlunparse((parsed.scheme, new_netloc, parsed.path, parsed.params, parsed.query, parsed.fragment))
logging.debug(f"모바일 주소로 변환: {new_url}")
return new_url
return url
def scrape_naver_blog(url):
logging.debug("스크래핑 프로세스 시작.")
# 1) URL을 모바일 버전으로 변환
mobile_url = convert_to_mobile_url(url)
logging.debug(f"최종 요청할 URL: {mobile_url}")
# 2) 요청 전 랜덤 딜레이 (1~3초)
delay = random.uniform(1, 3)
logging.debug(f"요청 전 {delay:.2f}초 대기.")
time.sleep(delay)
# 3) HTTP 헤더 설정 (User-Agent, Referer 등)
headers = {
"User-Agent": get_random_user_agent(),
"Referer": "https://m.blog.naver.com",
"Accept-Language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7"
}
logging.debug(f"요청 헤더: {headers}")
# 4) GET 요청
try:
logging.debug(f"URL로 GET 요청 전송: {mobile_url}")
response = requests.get(mobile_url, headers=headers, timeout=10)
logging.debug(f"응답 상태 코드: {response.status_code}")
except Exception as e:
logging.error(f"HTTP 요청 중 에러 발생: {e}")
return f"HTTP 요청 중 에러 발생: {e}"
if response.status_code != 200:
logging.error("200이 아닌 상태 코드 수신.")
return f"HTTP 요청 실패, 상태 코드: {response.status_code}"
# 5) HTML 파싱
logging.debug("HTML 파싱 시작.")
soup = BeautifulSoup(response.text, "html.parser")
# --------------------
# 제목 추출 로직
# --------------------
logging.debug("제목 추출 시도.")
# (A) 새 에디터 구조
title_text = None
title_div = soup.find("div", class_="se-module se-module-text se-title-text")
if title_div:
p_tag = title_div.find("p")
if p_tag:
span_tag = p_tag.find("span")
if span_tag:
title_text = span_tag.get_text(strip=True)
# (B) 구 에디터 구조: #postViewArea 내부 등
if not title_text:
post_view_area = soup.find("div", id="postViewArea")
if post_view_area:
candidate_title = post_view_area.find("span", class_="pcol1 itemSubjectBoldfont")
if candidate_title:
title_text = candidate_title.get_text(strip=True)
else:
h3_title = post_view_area.find("h3")
if h3_title:
title_text = h3_title.get_text(strip=True)
else:
strong_title = post_view_area.find("strong")
if strong_title:
title_text = strong_title.get_text(strip=True)
# (C) 그래도 없으면 이라도 사용
if not title_text:
head_title = soup.find("title")
if head_title:
title_text = head_title.get_text(strip=True)
else:
title_text = "제목을 찾을 수 없습니다."
logging.debug(f"최종 추출된 제목: {title_text}")
# --------------------
# 본문 추출 로직
# --------------------
logging.debug("본문 내용 추출 시도.")
content_text = None
# (A) 새 에디터 구조: div.se-main-container
content_div = soup.find("div", class_="se-main-container")
if content_div:
content_text = content_div.get_text(separator="\n", strip=True)
# (B) 구 에디터 구조: div#postViewArea
if not content_text:
old_content_div = soup.find("div", id="postViewArea")
if old_content_div:
content_text = old_content_div.get_text(separator="\n", strip=True)
# (C) 실패 시 안내
if not content_text:
content_text = "본문 내용을 찾을 수 없습니다."
logging.debug("본문 내용 추출 완료.")
# 제목 + 본문 결합
combined_text = f"제목: {title_text}\n\n본문:\n{content_text}"
logging.debug("스크래핑 프로세스 완료.")
return combined_text
# Gradio 인터페이스
logging.debug("Gradio 인터페이스 생성.")
iface = gr.Interface(
fn=scrape_naver_blog,
inputs=gr.Textbox(label="네이버 블로그 링크", placeholder="네이버 블로그 URL을 입력하세요"),
outputs=gr.Textbox(label="스크래핑 결과", lines=20),
title="네이버 블로그 스크래핑 도구",
description="네이버 블로그 링크를 입력하면 제목과 본문 내용을 추출합니다."
)
if __name__ == "__main__":
logging.debug("Gradio 앱 실행.")
iface.launch()