Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬 BeautifulSoup으로 웹 페이지 데이터 파싱하기: 기본 개념부터 실전 예제까지

BeautifulSoup은 웹 페이지에서 데이터를 구문 분석(파싱)하기 위해 사용되는 파이썬 서드파티 라이브러리입니다. 이 라이브러리는 다양한 소스로부터 데이터를 추출하고, 활용하며, 가공하는 과정인 웹 스크래핑(Web Scraping)에 매우 유용하게 쓰입니다.

웹 스크래핑은 단순한 데이터 수집을 넘어 여러 분야에서 폭넓게 활용되고 있습니다. 대표적인 활용 사례는 다음과 같습니다.

  • 연구 목적의 데이터 수집
  • 시장 트렌드 분석 및 비교
  • SEO(검색 엔진 최적화) 모니터링

BeautifulSoup 설치 방법

Windows 환경에서는 아래 명령어를 실행하여 BeautifulSoup을 손쉽게 설치할 수 있습니다.

pip install beautifulsoup4

실전 예제

다음은 Wikipedia의 'Algorithm' 문서에서 HTML을 가져와 본문 텍스트만 추출하는 예제 코드입니다.

import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
import urllib

url = 'https://en.wikipedia.org/wiki/Algorithm'
html = urlopen(url).read()
print("Reading the webpage...")

soup = BeautifulSoup(html, features="html.parser")
print("Parsing the webpage...")

for script in soup(["script", "style"]):
    script.extract()  # 불필요한 태그 제거

print("Extracting text from the webpage...")
text = soup.get_text()

print("Data cleaning...")
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = '\n'.join(chunk for chunk in chunks if chunk)
text = str(text)
print(text)

실행 결과

Reading the webpage...
Parsing the webpage...
Extracting text from the webpage...
Data cleaning...
Recursive C implementation of Euclid's algorithm from the above flowchart
Recursion
A recursive algorithm is one that invokes (makes reference to) itself repeatedly until a certain condition (also known as termination condition) matches, which is a method common to functional programming….
…..
Developers
Statistics
Cookie statement

코드 설명

위 예제의 동작 과정을 단계별로 살펴보면 다음과 같습니다.

  • 패키지 임포트: 필요한 패키지들을 가져오고 별칭(alias)을 지정합니다.
  • URL 정의: 데이터를 가져올 웹사이트 주소를 지정합니다.
  • 태그 제거: URL을 열어 HTML을 읽은 뒤, 'script' 태그 등 본문과 무관한 HTML 요소들을 제거합니다. 이렇게 하면 자바스크립트나 CSS 코드가 결과에 섞이지 않습니다.
  • 텍스트 추출: 'get_text' 함수를 사용하여 웹 페이지 데이터에서 순수 텍스트만 추출합니다.
  • 데이터 정제: 불필요한 공백과 유효하지 않은 문자열을 제거하여 깔끔한 텍스트를 만듭니다.
  • 결과 출력: 최종 정제된 텍스트를 콘솔에 출력합니다.

이처럼 BeautifulSoup을 활용하면 몇 줄의 코드만으로도 웹 페이지에서 원하는 텍스트 데이터를 효율적으로 추출할 수 있습니다. 특히 html.parser 외에도 lxml 같은 더 빠른 파서를 사용하면 대용량 문서 처리 시 성능을 더욱 향상시킬 수 있습니다.