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

Python newspaper 라이브러리로 뉴스 기사 스크랩과 큐레이션 자동화하기

웹 페이지에 담긴 콘텐츠는 데이터 마이닝, 정보 검색 등 다양한 분야에서 활용할 수 있는 귀중한 자원입니다. 특히 신문이나 잡지 웹사이트에서 기사 정보를 추출하려면 newspaper 라이브러리가 매우 유용합니다.

이 라이브러리의 핵심 목적은 신문 사이트를 비롯한 유사한 웹사이트에서 기사를 자동으로 추출하고 큐레이션하는 것입니다.

설치 방법

newspaper 라이브러리를 설치하려면 터미널에서 아래 명령어를 실행하세요.

$ pip install newspaper3k

lxml 의존성 패키지가 필요하다면 다음 명령어를 실행합니다.

$ pip install lxml

이미지 처리를 위한 PIL(Pillow)은 아래 명령어로 설치할 수 있습니다.

$ pip install Pillow

NLP(자연어 처리) 분석에 필요한 코퍼라(corpus) 데이터는 다음 명령으로 다운로드합니다.

$ curl https://raw.githubusercontent.com/codelucas/newspaper/master/download_corpora.py | python

기사에서 추출할 수 있는 정보

Python newspaper 라이브러리는 기사와 관련된 다양한 정보를 수집합니다. 대표적으로 다음과 같은 항목들이 포함됩니다.

  • 작성자 이름
  • 기사 내 주요 이미지
  • 게시 날짜
  • 기사에 포함된 동영상
  • 기사를 설명하는 키워드
  • 기사 요약문

기본 사용 예제

아래 코드는 WSJ(월스트리트저널) 기사 URL에서 작성자 이름을 추출하는 예제입니다.

# 필요한 라이브러리 임포트
from newspaper import Article

# 추출하고 싶은 기사의 URL
url = "https://www.wsj.com/articles/lawmakers-to-resume-stalled-border-security-talks-11549901117"

# 기사 객체 생성 후 다운로드
article = Article(url)
article.download()

# 기사를 파싱하여 작성자 이름 가져오기
article.parse()
print(article.authors)

실행 결과

['Kristina Peterson', 'Andrew Duehren', 'Natalie Andrews', 'Kristina.Peterson Wsj.Com', 'Andrew.Duehren Wsj.Com', 'Natalie.Andrews Wsj.Com']

게시일과 대표 이미지 추출하기

같은 방식으로 기사의 게시 날짜와 대표 이미지 URL도 손쉽게 확인할 수 있습니다.

# 게시 날짜 추출
print("Article Publication Date:")
print(article.publish_date)

# 대표 이미지 URL 추출
print(article.top_image)

실행 결과

https://images.wsj.net/im-51122/social

NLP로 키워드와 요약 추출하기

nlp() 메서드를 호출하면 기사 본문을 분석해 핵심 키워드와 자동 요약문을 얻을 수 있습니다.

print("Keywords in the article", article.keywords)
print("Article Summary", article.summary)

전체 통합 코드

지금까지 살펴본 기능을 하나로 묶은 전체 프로그램은 다음과 같습니다.

from newspaper import Article

url = "https://www.wsj.com/articles/lawmakers-to-resume-stalled-border-security-talks-11549901117"
article = Article(url)
article.download()
article.parse()

print(article.authors)
print("Article Publication Date:")
print(article.publish_date)
print("Major Image in the article:")
print(article.top_image)

article.nlp()
print("Keywords in the article")
print(article.keywords)
print("Article Summary")
print(article.summary)

실행 결과

['Kristina Peterson', 'Andrew Duehren', 'Natalie Andrews', 'Kristina.Peterson Wsj.Com', 'Andrew.Duehren Wsj.Com', 'Natalie.Andrews Wsj.Com']
Article Publication Date:
None
Major Image in the article:
https://images.wsj.net/im-51122/social
Keywords in the article
['state', 'spending', 'sweeping', 'southern', 'security', 'border', 'principle', 'lawmakers', 'avoid', 'shutdown', 'reach', 'weekendthe', 'fund', 'trump', 'union', 'agreement', 'wall']
Article Summary
President Trump made the case in his State of the Union address for the construction of a wall along the southern U.S. border, calling it a “moral issue.”
Photo: GettyWASHINGTON—Senior lawmakers said Monday night they had reached an agreement in principle on a sweeping deal to end a monthslong fight over border security and avoid a partial government shutdown this weekend.
The top four lawmakers on the House and Senate Appropriations Committees emerged after three closed-door meetings Monday and announced that they had agreed to a framework for all seven spending bills whose funding expires at 12:01 a.m. Saturday.

마무리

newspaper 라이브러리를 활용하면 단 몇 줄의 코드만으로 뉴스 기사의 작성자, 게시일, 대표 이미지, 키워드, 요약문까지 자동으로 수집할 수 있습니다. 뉴스 애그리게이터, 콘텐츠 큐레이션 서비스, 데이터 분석 파이프라인 등을 구축할 때 강력한 도구가 될 것입니다.