Akashic Records

학습사이트 http://quotes.toscrape.com/ BFS 크롤링 본문

Web Crawling for Beginners

학습사이트 http://quotes.toscrape.com/ BFS 크롤링

Andrew's Akashic Records 2024. 4. 24. 13:59
728x90

위는 파이썬 웹 크롤러 프로그램의 개념적 다이어그램을 나타낸 이미지입니다. 이 이미지는 컴퓨터 화면에 코드가 표시되고, 웹 서버와의 데이터 요청 및 응답을 상징하는 화살표가 흐름을 보여주는 모습을 단순하고 교육적인 스타일로 표현하고 있습니다. 컴퓨터는 'Web Crawler'로, 웹 서버는 'Website'로 레이블이 붙어 있습니다.

 

http://quotes.toscrape.com/ 사이트를 너비 우선 탐색(BFS) 방법으로 크롤링하고, 크롤링된 데이터를 엑셀 파일에 저장하는 파이썬 스크립트를 작성해드리겠습니다. 이 스크립트는 각 페이지에서 인용구, 저자, 태그를 추출하고, 설정된 최대 깊이(max_depth)까지 탐색합니다.

 

필요한 라이브러리 설치

다음 라이브러리를 설치하세요. requestsBeautifulSoup는 웹 크롤링을 위해, pandasopenpyxl은 엑셀 파일 작업을 위해 사용됩니다.

pip install beautifulsoup4 requests pandas openpyxl

 

너비 우선 탐색(BFS) 웹 크롤러 코드

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
from collections import deque
import pandas as pd

def extract_quotes(soup):
    """페이지에서 인용구, 저자, 태그를 추출합니다."""
    quotes_data = []
    quotes = soup.find_all('div', class_='quote')
    for quote in quotes:
        text = quote.find('span', class_='text').text
        author = quote.find('small', class_='author').text
        tags = [tag.text for tag in quote.find_all('a', class_='tag')]
        quotes_data.append({'text': text, 'author': author, 'tags': ', '.join(tags)})
    return quotes_data

def bfs_crawl(start_url, max_depth=3):
    """너비 우선 탐색(BFS)으로 사이트를 크롤링합니다."""
    queue = deque([(start_url, 0)])
    visited = set()
    all_quotes = []

    while queue:
        current_url, depth = queue.popleft()
        if depth > max_depth:
            continue
        if current_url in visited:
            continue
        visited.add(current_url)

        response = requests.get(current_url)
        soup = BeautifulSoup(response.text, 'html.parser')
        all_quotes.extend(extract_quotes(soup))

        # 다음 페이지 링크 찾기
        next_button = soup.find('li', class_='next')
        if next_button:
            next_url = next_button.find('a')['href']
            next_page_url = urljoin(current_url, next_url)
            queue.append((next_page_url, depth + 1))

    return all_quotes

# 크롤링 시작
start_url = 'http://quotes.toscrape.com/'
quotes = bfs_crawl(start_url, max_depth=2)

# 결과를 DataFrame으로 변환 후 Excel 파일로 저장
df = pd.DataFrame(quotes)
df.to_excel('quotes.xlsx', index=False, engine='openpyxl')

print("Crawling completed and data saved to Excel.")

실행 콘솔로그
저장된 엑셀 데이터

코드 설명

  1. 함수 extract_quotes:
    • BeautifulSoup 객체를 받아 해당 페이지에서 인용구, 저자, 태그를 추출합니다.
    • 각 인용구 정보를 리스트로 반환합니다.
  2. 함수 bfs_crawl:
    • 시작 URL에서부터 크롤링을 시작하여, 너비 우선 탐색 방식으로 모든 페이지를 방문합니다.
    • 각 페이지마다 extract_quotes 함수를 호출하여 인용구 정보를 수집합니다.
    • 'Next' 버튼을 찾아 다음 페이지의 URL을 큐에 추가하며, 최대 깊이(max_depth)까지 탐색합니다.
  3. 엑셀 파일 저장:
    • 수집된 모든 인용구 데이터를 pandas DataFrame으로 변환합니다.
    • DataFrame을 'quotes.xlsx' 파일로 저장합니다. 파일 작업에 openpyxl 엔진을 사용합니다.

이 스크립트는 지정된 깊이까지 http://quotes.toscrape.com/ 사이트의 모든 페이지를 방문하고 인용구 정보를 엑셀 파일로 저장합니다. 설정된 깊이는 크롤링을 멈출 지점을 결정합니다.

728x90
Comments