[업무 자동화]/파이썬

[파이썬] 뉴스 기사 수집하기(feat. 코드 포함)

시간 확보러 2024. 10. 27. 08:00
728x90

 

파이썬을 통한 뉴스기사 수집하는 건 평소에 필요하지 않는다.

그 이유는 굳이 할 필요가 없기 때문이다.

 

하지만 뉴스기사를 분석해야 한다면??

꼭 필요한 기술이다.

수백 개의 URL을 일일이 눌러가면서 작업을 하기에는 시간이 많이 소요가 된다.

이번 연습사례는 뉴스기사를 크롤링 하는데 유용한 사례이다.

 

 

□파이썬 코드

import requests
from bs4 import BeautifulSoup
code = requests.get(f"http://underkg.co.kr/news")
soup = BeautifulSoup(code.text, "html.parser")
title = soup.select("h1.title > a")
for i in title:
    print(f"제목 : {i.text}")
    news_url=i.attrs['href']
    print(f"링크 : {news_url}")
    code_news=requests.get(news_url)
    soup_news=BeautifulSoup(code_news.text, "html.parser")
    content = soup_news.select_one("div.read_body")
    print(content.text)
    print(content.text.replace("\n", "").strip())
    print("------------------------------------------")

728x90