Python을 활용한 웹 스크래핑 및 자동화 인증

이미지 다운로드 유틸리티 구현

웹 리소스를 로컬에 저장하는 기본적인 기능부터 시작합니다. requests 라이브러리를 활용하여 원격 이미지를 효율적으로 다운로드하는 방법을 살펴봅니다.

import requests

def fetch_remote_image(target_url, destination_path):
    """원격 이미지를 지정된 경로에 저장"""
    server_response = requests.get(url=target_url)
    with open(destination_path, 'wb') as output_stream:
        output_stream.write(server_response.content)

설정 파일 구성

프로젝트 전역에서 사용하는 상수들을 중앙 집중화하여 관리합니다.

# config.py
BROWSER_HEADER = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'

TARGET_DOMAIN = 'https://dig.chouti.com/'

콘텐츠 추출 및 저장

BeautifulSoup을 이용해 HTML 문서를 파싱하고, 뉴스 항목에서 필요한 메타데이터를 추출합니다. 추출한 데이터는 텍스트 파일에 기록하고, 관련 이미지는 별도로 저장합니다.

import requests, os
from bs4 import BeautifulSoup
import config
from helpers.image_fetcher import fetch_remote_image

response = requests.get(
    url=config.TARGET_DOMAIN,
    headers={'user-agent': config.BROWSER_HEADER}
)

html_parser = BeautifulSoup(response.text, 'html.parser')

content_containers = html_parser.find_all(name='div', attrs={"id": 'content-list'})
for container in content_containers:
    news_entries = container.find_all(name='div', attrs={'class': 'item'})
    for entry in news_entries:
        detail_sections = entry.find_all(name='div', attrs={'class': 'news-content'})
        for section in detail_sections:
            article_link = section.find(name='a').attrs.get('href')
            meta_div = section.find(name='div', attrs={'class': 'part2'})
            thumbnail_url = meta_div['share-pic']
            headline = meta_div['share-title']
            description = section.find(name='span').text

            filename = thumbnail_url.rsplit('/', maxsplit=1)[1]
            local_path = os.path.join('storage/images', filename)

            fetch_remote_image(thumbnail_url, local_path)

            with open('storage/articles.txt', 'a', encoding='utf-8') as archive:
                archive.write(f"{article_link}\n{headline}\n{description}\n")

세션 기반 인증 및 상호작용

웹 애플리케이션에 프로그래밍 방식으로 접근하려면 세션 쿠키를 올바르게 처리해야 합니다. 로그인 과정에서 발급된 쿠키를 후속 요청에 재사용하는 패턴을 구현합니다.

"""
자동화된 인증 흐름 구현
"""
import requests
import config

# ==================== 단계 1: 초기 세션 확보 ====================
landing_page = requests.get(
    url='https://dig.chouti.com/',
    headers={'user-agent': config.BROWSER_HEADER}
)
session_tokens = landing_page.cookies.get_dict()
print(f"획득한 세션: {session_tokens}")

# ==================== 단계 2: 자격 증명 제출 ====================
auth_result = requests.post(
    url='https://dig.chouti.com/login',
    headers={'user-agent': config.BROWSER_HEADER},
    data={
        'phone': '86' + '18310189881',
        'password': 'abcd1234',
        'oneMonth': 1
    },
    cookies=session_tokens
)
print(auth_result.text)

# ==================== 단계 3: 인증된 작업 수행 ====================
interaction = requests.post(
    url='https://dig.chouti.com/link/vote?linksId=20868591',
    headers={'user-agent': config.BROWSER_HEADER},
    cookies=session_tokens
)
print(interaction.text)

핵심 개념 정리

  • 쿠키 지속성: 초기 GET 요청에서 수집한 쿠키를 로그인 및 후속 작업에 전달하여 세션 연속성을 유지
  • User-Agent 위장: 브라우저 식별자를 설정하여 서버의 봇 차단 메커니즘 우회
  • 바이너리 쓰기 모드: 이미지 저장 시 'wb' 모드 사용으로 바이트 데이터 무결성 보장
  • 계층적 파싱: DOM 트리를 순차적으로 탐색하여 특정 데이터 영역 정확히 추출

태그: python requests BeautifulSoup Web Scraping Session Management

5월 22일 07:46에 게시됨