[Python] trafilatura 라이브러리로 크롤링 쉽게 하기

웹 크롤링을 아주아주 간단하게 할 수 있도록 해주는 Python 라이브러리, trafilatura의 특징과 사용법에 대해 알아봅니다.

[Python] trafilatura 라이브러리로 크롤링 쉽게 하기
Photo by Gareth Davies / Unsplash

trafilatura는 웹 크롤링을 쉽고 효율적으로 수행할 수 있게 해주는 Python 라이브러리입니다. trafilatura를 사용하면 HTML 문서에서 제목과 본문처럼 중요한 텍스트를 추출하거나 JSON 형식으로 데이터를 구조화하는 등의 작업을 쉽게 처리할 수 있습니다.

trafilatura의 특징

  1. 간결성: 최소한의 코드로 HTML 파싱과 텍스트 추출을 수행할 수 있습니다. BeautifulSoup 처럼 해당 페이지의 HTML 태그 구조를 파악하고, 일일이 태그를 지정하지 않아도 되므로 번거로움이 조금 덜합니다.
  2. 다양한 출력 형식: JSON, XML 등 다양한 형식으로 데이터를 구조화하여 출력할 수 있어 후속 처리가 편리합니다.
  3. 다양한 옵션: HTML 파싱 및 텍스트 추출에 있어서, 하이퍼링크를 제외하거나 글쓴이, 날짜 등 메타데이터를 포함하는 등 다양한 세부 설정이 가능합니다.

trafilatura 사용 예시

아래 예시는 페이지를 읽어서 본문 내용을 plain text로 추출하는 기본적인 예시입니다.

from trafilatura import fetch_url, extract

# grab a HTML file to extract data from
downloaded = fetch_url('https://github.blog/2019-03-29-leader-spotlight-erin-spiceland/')

# output main content and comments as plain text
result = extract(downloaded)
print(result)

출력 형식을 지정하거나, 댓글 포함 여부와 메타데이터 포함 여부를 지정하는 방법은 아래를 참조하세요.

# change the output format to XML (allowing for preservation of document structure)
>>> result = extract(downloaded, output_format="xml")

# discard potential comments, extract metadata and change the output to JSON
>>> extract(downloaded, output_format="json", include_comments=False)

# set the output to Markdown and extract metadata
>>> extract(downloaded, output_format="markdown", with_metadata=True)

마치며

이번 포스팅에서는 손쉬운 웹 크롤링을 위한 파이썬 라이브러리 trafilatura의 간단한 사용법을 알아보았습니다. 저는 이를 이용하여 AI agent를 위한 웹 페이지 본문 내용 추출 도구를 만들어 보려고 합니다 👍

See also

A Python package & command-line tool to gather text on the Web — Trafilatura 2.0.0 documentation
Trafilatura is a Python package and command-line tool designed to gather text on the Web. Its main applications are web crawling, downloads, scraping, and extraction of main texts, comments and metadata.