CodeGym /자바 코스 /Python SELF KO /정기적인 데이터 수집을 위한 자동화 작업

정기적인 데이터 수집을 위한 자동화 작업

Python SELF KO
레벨 40 , 레슨 1
사용 가능

1. 날씨 API 사용하기

이제 기본적인 내용을 익혔으니, 현실적인 시나리오를 살펴보죠. 매 30분마다 날씨 데이터를 수집해야 한다고 상상해 봅시다. 이를 위해 날씨 데이터를 얻는 API를 사용할 거예요. 물론, 학습 목적으로 실제 API 사용이 제한될 수도 있으니, 어떻게 작동할지 그려봅시다.

OpenWeather API를 사용해 현재 날씨 가져오기

이 예제는 requests를 사용해 OpenWeather API로 특정 도시의 날씨 데이터를 가져오는 방법을 보여줘요.

Python

import schedule
import time
import requests

def fetch_weather(city):
    api_key = "YOUR_API_KEY"  # 자신의 OpenWeather API 키로 교체하세요
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"

    try:
        response = requests.get(url)
        response.raise_for_status()
        data = response.json()
        temperature = data["main"]["temp"]
        weather_description = data["weather"][0]["description"]
        print(f"{city}의 현재 온도: {temperature}°C")
        print(f"날씨 설명: {weather_description}")
    except requests.exceptions.RequestException as e:
        print(f"날씨 데이터를 가져오는 중 오류 발생: {e}")

def fetch_weather_of_london():
    fetch_weather("London")

# 매 30분마다 작업 실행 설정
schedule.every(30).minutes.do(fetch_weather_of_london)

while True:
    schedule.run_pending()
    time.sleep(1)

여기서는 OpenWeather API에 GET 요청을 보내 특정 도시의 현재 날씨를 가져와요. 응답 받은 JSON에서 온도와 날씨 설명을 추출해 화면에 출력합니다. YOUR_API_KEY를 자신의 API 키로 교체하는 것을 잊지 마세요.

API를 사용해 현재 환율 가져오기

이 예제에서는 requests를 사용해 API로부터 현재 환율 데이터를 가져와요.

Python

import schedule
import time
import requests

def fetch_exchange_rate():
    url = "https://api.exchangerate-api.com/v4/latest/USD"
    try:
        response = requests.get(url)
        response.raise_for_status()  # 요청 성공 여부 확인
        data = response.json()
        usd_to_eur = data["rates"]["EUR"]
        print(f"USD에서 EUR로의 현재 환율: {usd_to_eur}")
    except requests.exceptions.RequestException as e:
        print(f"데이터를 가져오는 중 오류 발생: {e}")

# 매 10분마다 작업 실행 설정
schedule.every(10).minutes.do(fetch_exchange_rate)

while True:
    schedule.run_pending()
    time.sleep(1)

여기서는 API로부터 환율 데이터를 GET 요청으로 받아 JSON 포맷으로 반환됩니다. JSON 응답에서 USD에서 EUR로의 환율을 추출해 화면에 출력합니다. 다른 통화쌍의 데이터를 수집하려면 data["rates"]의 키를 변경하면 돼요.

이 스크립트를 통해 우리는 날씨와 환율 데이터를 지속적으로 수집할 수 있어요. 시작하기에 나쁘지 않죠?

실제 활용 사례

데이터 수집 자동화는 여러 상황에서 유용하게 사용될 수 있어요:

  • 서버 상태 모니터링: 서버 상태를 자동으로 점검하면 문제 발생 전에 이를 알 수 있어요.
  • 소셜 미디어 데이터 수집: 트렌드 분석 및 브랜드 언급 추적.
  • 환율 추적: 환율 변동은 비즈니스나 개인 용도로 유용할 수 있어요.

2. 웹 데이터 자동 수집 예제

웹 페이지에서 데이터를 수집하고 싶다면 어떨까요? 예를 들어, 정기적으로 뉴스 업데이트를 확인한다고 합시다. BeautifulSouprequests는 이런 작업을 도와줄 거예요.

웹 페이지에서 데이터 수집

만약 뉴스 헤드라인을 수집하고 싶다면? 아래처럼 진행할 수 있어요:

Python

import requests
from bs4 import BeautifulSoup

def fetch_news():
    response = requests.get("http://example.com/news")
    soup = BeautifulSoup(response.content, 'html.parser')
    for headline in soup.find_all('h2', class_='news'):
        print(headline.text)

schedule.every().hour.do(fetch_news)

while True:
    schedule.run_pending()
    time.sleep(1)

이 예제에서 우리는 매 60분마다 웹 페이지를 확인하고 뉴스 헤드라인을 출력합니다. 최신 정보를 얻는 과정을 훨씬 간단하게 만들어 줘요.

웹사이트에서 뉴스 헤드라인 수집하기

이 예제에서는 requests를 사용해 HTML 페이지를 다운로드하고 BeautifulSoup로 뉴스 헤드라인을 파싱할 거예요.

Python

import requests
from bs4 import BeautifulSoup

def fetch_news_headlines():
    url = "https://www.bbc.com/news"
    try:
        response = requests.get(url)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')
        
        headlines = soup.find_all('h3')  # 모든 <h3> 태그 찾기 (보통 뉴스 헤드라인이 위치함)
        print("BBC의 최신 뉴스 헤드라인:")
        for headline in headlines[:5]:  # 첫 5개 헤드라인만 가져오기
            print("-", headline.get_text(strip=True))
    except requests.exceptions.RequestException as e:
        print(f"데이터를 가져오는 중 오류 발생: {e}")

fetch_news_headlines()

여기서는 BBC News 페이지를 로드해 BeautifulSoup를 이용해 모든 <h3> 태그를 검색합니다. 뉴스 헤드라인 5개를 출력하며, strip=True로 불필요한 공백과 문자를 제거해요.

온라인 쇼핑몰에서 상품 가격 데이터 수집

이 예제는 Amazon 또는 다른 쇼핑몰의 상품 가격 데이터를 추출하는 방법이에요. requests를 사용해 페이지를 요청하고, BeautifulSoup를 사용해 가격을 파싱합니다.

Python

import requests
from bs4 import BeautifulSoup

def fetch_product_price(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36"
    }
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        
        soup = BeautifulSoup(response.text, 'html.parser')
        product_name = soup.find('span', {'id': 'productTitle'}).get_text(strip=True)
        price = soup.find('span', {'class': 'a-price-whole'}).get_text(strip=True)
        
        print(f"상품: {product_name}")
        print(f"가격: {price} 원")
    except requests.exceptions.RequestException as e:
        print(f"데이터를 가져오는 중 오류 발생: {e}")
    except AttributeError:
        print("상품 또는 가격 정보를 찾을 수 없음")

# 상품 링크 예제
fetch_product_price("https://www.amazon.com/dp/B08N5WRWNW")

이 예제에서 우리는 User-Agent 헤더를 포함한 GET 요청을 보내 차단을 방지합니다. 그 다음 BeautifulSoup를 사용해 id="productTitle"로 상품명을 찾아내고 class="a-price-whole"로 상품 가격을 검색합니다. strip=True로 불필요한 공백을 제거해요.

코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION