고급 Python 웹 스크레이퍼

Python으로 고급 웹 스크레이퍼를 구축해 보세요. 페이지 데이터를 추출하고, 사용자 에이전트 블록을 처리하고, 속도 제한을 관리하고, 출력을 구조화하는 방법을 알아보세요.

에디터에서 사용해 보세요

개요

웹 스크래핑에는 프로그래밍 방식으로 웹 페이지를 가져오고 HTML 구조를 구문 분석하여 특정 데이터를 추출하는 작업이 포함됩니다. Python에서는 전통적으로 `requests`와 `BeautifulSoup`을 사용하여 이를 수행합니다.

고급 스크레이퍼에는 강력한 구성이 필요합니다. 단순히 페이지를 요청하면 차단 또는 IP 금지가 발생할 수 있으며, 사용자 지정 사용자 에이전트와 같은 헤더 사용자 지정이 필요하고 임의의 지연 간격이 도입될 수 있습니다.

이 대화형 예제는 유효성 검사를 통해 모의 데이터 스크래핑을 모방합니다. 중첩된 컨테이너를 찾고, 네트워크 시간 초과를 처리하고, 출력 데이터를 깔끔한 목록으로 구조화하는 방법을 보여줍니다.

코드 및 실행 출력

사용자 정의 헤더, 시간 초과 관리 및 HTML 파서 구조를 갖춘 웹 스크래핑 루틴입니다.

import requests
from bs4 import BeautifulSoup
import time

def scrape_quotes():
    # Mock URL designed for scraping practice
    url = "https://quotes.toscrape.com/"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    }
    
    print(f"Initiating request to: {url}...")
    try:
        # Request with timeout protection
        response = requests.get(url, headers=headers, timeout=5)
        response.raise_for_status()
        
        soup = BeautifulSoup(response.text, "html.parser")
        quotes = soup.find_all("div", class_="quote", limit=3)
        
        results = []
        for q in quotes:
            text = q.find("span", class_="text").text
            author = q.find("small", class_="author").text
            tags = [t.text for t in q.find_all("a", class_="tag")]
            results.append({
                "quote": text,
                "author": author,
                "tags": tags
            })
            
        print("Scrape completed successfully!\n")
        for idx, item in enumerate(results):
            print(f"Quote {idx+1}: {item['quote']}")
            print(f"  Author: {item['author']}")
            print(f"  Tags:   {', '.join(item['tags'])}\n")
            
    except requests.exceptions.RequestException as e:
        print(f"Network error occurred: {e}")

scrape_quotes()
터미널 출력
Initiating request to: https://quotes.toscrape.com/...
Scrape completed successfully!

Quote 1: “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”
  Author: Albert Einstein
  Tags:   change, deep-thoughts, thinking

Quote 2: “It is our choices, Harry, that show what we truly are, far more than our abilities.”
  Author: J.K. Rowling
  Tags:   abilities, choices

Quote 3: “There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”
  Author: Albert Einstein
  Tags:   inspirational, life, live, miracle

단계별 구현

  • 쇼핑 카탈로그 전체의 가격 모니터링 및 추적
  • 포럼 리뷰 데이터를 수집하여 감성 분석
  • 학술 연구 데이터 세트 생성

자주 묻는 질문

robots.txt란 무엇인가요?

검색 로봇과 크롤러가 크롤링을 허용하거나 금지하는 경로를 나타내는 도메인 루트에 있는 텍스트 파일입니다. 스크레이퍼를 작성하기 전에 항상 읽어야 합니다.

JavaScript를 통해 동적으로 렌더링된 페이지를 어떻게 긁을 수 있나요?

표준 요청은 정적 HTML만 가져옵니다. Javascript가 많은 페이지를 구문 분석하려면 Playwright 또는 Selenium과 같은 브라우저 자동화 도구를 사용해야 합니다.

관련 주제