파이썬 인터넷상에 있는 파일 크롤링 수집 자동화에 대해

2025. 5. 12. 01:03IT & Programming/python

파이썬에서는 인터넷에 있는 파일(예: 이미지, 텍스트, CSV, JSON 등)을 다운로드하거나 읽어들이는 작업을 아주 쉽게 할 수 있습니다. 이 기능은 웹 크롤링, 데이터 수집, 자동화된 파일 저장 등에 매우 유용합니다.

아래는 인터넷상의 파일을 처리하기 위한 주요 모듈과 방법을 체계적으로 정리한 내용입니다.


1. 사용되는 주요 모듈

모듈명 용도 설명

requests HTTP 요청 (파일 다운로드, API 호출 등)
urllib 내장 HTTP 모듈 (간단한 요청 처리)
os, pathlib 로컬 파일 저장 경로 관리
shutil 파일 복사 및 이동
pandas 웹의 CSV, Excel, JSON 불러오기
BeautifulSoup, selenium 웹페이지 구조 파악 후 파일 URL 추출용 (크롤링 시)

2. requests 모듈로 파일 다운로드

예제 1: 텍스트 파일 다운로드

import requests

url = "https://www.w3.org/TR/PNG/iso_8859-1.txt"
response = requests.get(url)

with open("sample.txt", "w", encoding="utf-8") as f:
    f.write(response.text)

예제 2: 이미지 파일 다운로드

url = "https://www.example.com/image.jpg"
response = requests.get(url)

with open("image.jpg", "wb") as f:
    f.write(response.content)
  • text: 문자열 응답
  • content: 바이너리 응답 (이미지, PDF, ZIP 등)

3. urllib로 파일 처리 (표준 내장 모듈)

import urllib.request

url = "https://example.com/data.csv"
urllib.request.urlretrieve(url, "data.csv")  # 간단한 다운로드
  • requests보다 기능은 단순하지만, 외부 설치 필요 없이 사용 가능

4. pandas로 직접 웹의 CSV/Excel 읽기

CSV 파일 웹에서 바로 읽기

import pandas as pd

url = "https://people.sc.fsu.edu/~jburkardt/data/csv/airtravel.csv"
df = pd.read_csv(url)
print(df.head())

Excel 파일 (.xlsx)도 마찬가지

df = pd.read_excel("https://file-examples.com/wp-content/uploads/2017/02/file_example_XLSX_10.xlsx")

5. JSON API 응답 처리

import requests

url = "https://jsonplaceholder.typicode.com/users"
response = requests.get(url)
data = response.json()

for user in data:
    print(user["name"])
  • .json()은 응답 내용을 자동으로 파싱해 dict/list 구조로 반환

6. 대용량 파일 다운로드 (스트리밍 방식)

url = "https://example.com/largefile.zip"
with requests.get(url, stream=True) as r:
    with open("largefile.zip", "wb") as f:
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)
  • stream=True를 사용하면 대용량 파일도 메모리 부담 없이 다운로드 가능

7. URL로 파일 이름 자동 추출

from urllib.parse import urlparse
import os

url = "https://example.com/files/data.csv"
filename = os.path.basename(urlparse(url).path)
print(filename)  # 'data.csv'

8. 파일 존재 여부 확인 후 저장

import os
if not os.path.exists("sample.csv"):
    response = requests.get(url)
    with open("sample.csv", "wb") as f:
        f.write(response.content)

9. 주요 응용 사례

상황 처리 방식

이미지 저장 requests.get(url).content 사용 후 wb 저장
API JSON 수집 requests.get().json()
공공 데이터 포털 XLSX pandas.read_excel(URL)
PDF/ZIP 다운로드 requests.get(stream=True)
자동 저장 경로 관리 os, pathlib 모듈 조합

정리

기능 사용 모듈

텍스트/이미지 다운로드 requests, urllib
웹에서 CSV, Excel 불러오기 pandas
JSON 응답 처리 requests, json
파일명 자동 추출 urllib.parse, os
대용량 다운로드 requests(stream=True)
저장 경로 관리 및 확인 os, pathlib

 

좋습니다. 이번에는 파이썬으로 인터넷상의 파일을 자동으로 수집·저장·정리하는 과정을 실전 예제 중심으로 확장해서 설명드리겠습니다.


1. 공공데이터 포털 CSV 자동 수집 예제

공공기관에서는 .csv, .xls(x), .json 형태의 데이터 파일을 직접 제공하는 경우가 많습니다. 이를 자동으로 수집하고 저장하는 코드를 아래처럼 구성할 수 있습니다.

import requests
import os

# 다운로드할 URL 목록
csv_urls = [
    "https://www.data.go.kr/sample1.csv",
    "https://www.data.go.kr/sample2.csv"
]

# 저장 폴더 설정
save_dir = "downloads"
os.makedirs(save_dir, exist_ok=True)

for url in csv_urls:
    filename = url.split("/")[-1]
    filepath = os.path.join(save_dir, filename)

    if not os.path.exists(filepath):
        response = requests.get(url)
        with open(filepath, "wb") as f:
            f.write(response.content)
        print(f"{filename} 저장 완료")
    else:
        print(f"{filename} 이미 존재함")

2. 웹 이미지 일괄 다운로드 자동화

import requests
from bs4 import BeautifulSoup
import os

url = "https://example.com/gallery"
res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")

img_tags = soup.find_all("img")
os.makedirs("images", exist_ok=True)

for i, tag in enumerate(img_tags):
    src = tag.get("src")
    if not src.startswith("http"):
        src = "https://example.com" + src
    img = requests.get(src)
    with open(f"images/img_{i+1}.jpg", "wb") as f:
        f.write(img.content)
  • BeautifulSoup을 이용하여 HTML 내 <img> 태그를 모두 가져온 후, 이미지 파일을 자동 저장
  • 상대경로 처리 주의 필요

3. API에서 주기적으로 파일 받아 저장하기 (스케줄링 가능)

import requests
from datetime import datetime
import os

today = datetime.now().strftime("%Y%m%d")
url = f"https://example.com/data?date={today}"

res = requests.get(url)
filename = f"daily_data_{today}.json"

if res.status_code == 200:
    with open(filename, "w", encoding="utf-8") as f:
        f.write(res.text)
    print(f"{filename} 저장 완료")
else:
    print("데이터를 불러올 수 없습니다.")
  • 공공데이터 Open API에서 날짜별 자료 제공 시 유용
  • crontab이나 schedule 모듈을 이용해 자동 실행 가능

4. pathlib로 디렉토리 정리

from pathlib import Path
import shutil

base = Path("downloads")
backup = base / "backup"
backup.mkdir(exist_ok=True)

for file in base.glob("*.csv"):
    shutil.move(str(file), str(backup / file.name))
  • 특정 파일 패턴만 골라서 이동 가능 (*.csv, *.xlsx 등)
  • shutil.move()로 이동, copy()는 복사

5. 실전 미니 프로젝트: 자동 보고서 수집 시스템

목표

  • 매일 특정 URL에서 보고서 .xlsx 파일 다운로드
  • 날짜별로 폴더 생성
  • 이미 존재하면 건너뜀

구현 코드

import requests
from datetime import datetime
from pathlib import Path

today = datetime.now().strftime("%Y-%m-%d")
url = "https://example.com/report.xlsx"
save_dir = Path("reports") / today
save_dir.mkdir(parents=True, exist_ok=True)

filepath = save_dir / "daily_report.xlsx"

if not filepath.exists():
    res = requests.get(url)
    filepath.write_bytes(res.content)
    print("보고서 저장 완료:", filepath)
else:
    print("이미 보고서가 존재합니다.")

6. 추가 팁: 사용자 에이전트 설정

일부 서버는 봇을 막기 위해 사용자 에이전트를 확인합니다. 이때는 headers를 지정해줍니다.

headers = {'User-Agent': 'Mozilla/5.0'}
res = requests.get(url, headers=headers)

요약 정리

자동화 대상 방법

CSV/Excel 다운로드 requests, pandas.read_csv()
이미지 일괄 저장 BeautifulSoup + requests
JSON API 수집 requests.get().json() + datetime
폴더 자동 정리 pathlib, os, shutil
스케줄링 처리 schedule, cron, datetime

 

반응형