연합뉴스 정치기사 RSS로 정치뉴스 적재 코드를 만들었습니다.
이 코드는 코랩에서 구글드라이브로 바로 넘어가게 돼 있어서, 관리 및 공유에 편리합니다.
코드는 실행시킬때만 작동하는데, 새로운 뉴스가 기존 뉴스 상단에 배치되는 방식이니
누적으로 살펴보기 좋습니다.
효율적인 뉴스 데이터 수집: RSS와 구글 코랩의 시너지
RSS를 사용한 뉴스 기사 크롤링은 간단하면서도 효율적입니다. RSS 피드는 웹 콘텐츠를 구조화된 형식으로 제공하여 복잡한 파싱 없이도 최신 업데이트를 쉽게 추출할 수 있게 합니다. 이러한 단순성은 뉴스 기사를 지속적으로 가져오는 데 이상적입니다.
제공된 코드는 구글 콜랩에서 파이썬을 활용하여 연합뉴스의 RSS 피드에서 기사를 가져와 구글 시트 파일에 저장합니다. 이 과정은 필요한 라이브러리를 설치하고 구글 드라이브 인증으로 시작됩니다. 그 다음, 코드는 requests와 xmltodict를 사용하여 RSS 피드를 가져와 파싱합니다. 지정된 구글 시트를 열거나 존재하지 않는 경우 새로 만들고 헤더 행을 추가합니다. 기사들은 시트에 추가되며, 중복 확인을 통해 새로운 기사가 상단에 나타나도록 합니다. 이러한 접근 방식은 뉴스 기사를 구조화된 형식으로 지속적으로 업데이트하는 원활하고 효율적인 방법을 보장합니다.
단계별 진행
1. 필요한 라이브러리 설치: gspread, requests 및 xmltodict를 설치합니다.
2. Google Drive로 인증: Google Colab에 내장된 방법을 사용하여 인증을 처리합니다.
3. RSS 피드 가져오기: requests 라이브러리를 사용하여 RSS 피드를 가져옵니다.
4. RSS 피드 구문 분석: xmltodict를 사용하여 피드를 구문 분석합니다.
5. Google 시트 업데이트: Google 시트에 새 기사를 추가하여 최신 기사가 맨 위에 오도록 합니다.
아래는 코드 전문
# Install necessary libraries
!pip install gspread requests xmltodict
# Import necessary libraries
import gspread
from google.colab import auth
from google.auth import default
import requests
import xmltodict
import datetime
# Authenticate and create the PyDrive client.
auth.authenticate_user()
creds, _ = default()
gc = gspread.authorize(creds)
# Function to fetch and parse RSS feed
def fetch_rss_feed(url):
response = requests.get(url)
data = xmltodict.parse(response.content)
articles = data['rss']['channel']['item']
return articles
# Function to update Google Sheet
def update_google_sheet(sheet_name, articles):
try:
# Open the Google Sheet
sheet = gc.open(sheet_name).sheet1
except gspread.SpreadsheetNotFound:
# If the sheet does not exist, create a new one
sheet = gc.create(sheet_name).sheet1
# Add header row
sheet.append_row(["Title", "Link", "Publication Date"])
# Get existing rows
existing_rows = sheet.get_all_values()
existing_titles = [row[0] for row in existing_rows[1:]]
# Append new articles if not already in the sheet
for article in reversed(articles): # reverse to maintain order
title = article['title']
if title not in existing_titles:
link = article['link']
pub_date = article['pubDate']
sheet.insert_row([title, link, pub_date], 2) # insert at top (after header)
# Fetch RSS feed
rss_url = "https://www.yna.co.kr/rss/politics.xml"
articles = fetch_rss_feed(rss_url)
# Update Google Sheet with the fetched articles
sheet_name = "Yonhap News Articles"
update_google_sheet(sheet_name, articles)
print("Google Sheet updated successfully!")
'python' 카테고리의 다른 글
Python으로 PowerPoint 프레젠테이션 자동화하기: 장단점 및 실전 가이드 (0) | 2024.07.04 |
---|---|
python이 엑셀보다 나은 10가지 (0) | 2024.07.04 |
"Python으로 텍스트를 음성으로 변환하기: gTTS와 ffmpeg 사용법" (1) | 2024.06.30 |
파이썬으로 만든 '텍스트 to 음성' 코드 (0) | 2024.06.28 |
텍스트를 음성으로 변환하여 파일로 저장하는 파이썬 스크립트 가이드 (0) | 2024.06.28 |