학교 과제로 매일 3개씩 경제 기사 읽고 요약하라고 하는데 너무 귀찮아서 코딩으로 해결함!
나중에 시간되면 클라우드로 배포해서 코드 실행 한번으로 매일 자동으로 파일 저장하게 만들어야겠다.
import requests
from bs4 import BeautifulSoup
import openai
import random
from datetime import datetime
# OpenAI API 설정
openai.api_key = ''
# 매일경제 메인 페이지 URL
main_url = 'https://www.mk.co.kr/news/ranking/economy/'
# 1. 인기 기사 링크 가져오기
def get_popular_articles():
response = requests.get(main_url)
soup = BeautifulSoup(response.text, 'html.parser')
# 기사 링크 추출
article_links = []
for i in range(1, 11):
article = soup.select(f'#container > section > div > section > div.sec_body > div > ul > li:nth-child({i}) > a')
if article:
article_links.append(article[0]['href'])
return article_links
# 2. 기사 제목과 본문 추출
def get_article_details(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 제목 추출
title_tag = soup.select_one('#container > section.contents > div.news_detail_head_group.type_none_bg > section > div > div > div > h2')
title = title_tag.get_text().strip() if title_tag else '제목을 찾을 수 없습니다.'
# 본문 추출
content_tag = soup.select_one('div.news_cnt_detail_wrap')
content = content_tag.get_text() if content_tag else '본문을 찾을 수 없습니다.'
return title, content
# 3. OpenAI로 요약 요청
def summarize_article_with_openai(content):
try:
response = openai.chat.completions.create(
model="gpt-3.5-turbo", # GPT 모델 사용
messages=[{
"role": "user",
"content": f"다음 기사의 본문을 보고 그 기사에 대한 내 생각을 만들어서 의견을 3~4줄로 요약해주세요:\n\n{content}"
}]
)
ai_response = response.choices[0].message.content
return ai_response
except Exception as e:
return f"Error: {str(e)}"
# 메인 함수
def main():
# 인기 기사 링크 10개 가져오기
article_links = get_popular_articles()
# 3개 랜덤 기사 선택
selected_links = random.sample(article_links, 3)
# 문서 작성
document = ""
# 각 기사의 제목과 본문을 요약해서 출력
for idx, url in enumerate(selected_links, 1):
print(f"기사 {idx} URL: {url}")
# 기사 제목과 본문 가져오기
title, content = get_article_details(url)
# 본문을 요약
summary = summarize_article_with_openai(content)
print(f"기사 {idx} 제목: {title}")
print(f"기사 {idx} 요약: {summary}")
# 문서에 추가
document += f"기사 {idx} 링크: {url}\n"
document += f"기사 {idx} 제목: {title}\n"
document += f"기사 {idx} 요약: {summary}\n"
document += '-' * 50 + '\n'
# 현재 날짜를 가져와 파일명에 포함
current_date = datetime.now().strftime("%Y-%m-%d")
file_name = f"article_summary_{current_date}.txt"
# 결과 문서를 텍스트 파일로 저장 (덮어쓰기)
with open(file_name, 'w', encoding='utf-8') as file:
file.write(document)
print(f"\n결과가 '{file_name}' 파일에 저장되었습니다.")
if __name__ == '__main__':
main()