python/자동화

[Python] 뉴스의 제목, 날짜, 본문 데이터 가져오기 - 1회성 (매크로아님)

sillon 2022. 9. 28. 21:49
728x90
반응형

target_url 변수에 해당 링크를 입력하면 됩니다.

from urllib.request import urlopen
from bs4 import BeautifulSoup

news_info = {"title": "",
             "content": "",
             "data": ""

             }

def news_content_crawl(target_url):
    html = urlopen(target_url)
    bsObject = BeautifulSoup(html, "html.parser")

    title = bsObject.find("div", {"class":"media_end_head_title"}).get_text()
    content = bsObject.find("div", {"class":"go_trans _article_content"}).get_text()
    date = bsObject.find("span", {"class":"media_end_head_info_datestamp_time _ARTICLE_DATE_TIME"}).get_text()

    news_info = { "title" : title,
                  "content": content,
                  "data": date
                }

    for i in news_info:
        news_info[i] = news_info[i].replace("\n","")
        news_info[i] = news_info[i].replace("\\'", "")

    print(news_info)


if __name__ =="__main__":
    target_url = "https://n.news.naver.com/mnews/article/082/0001176080?sid=100"
    news_content_crawl(target_url)

 

\n (줄바꿈) 제거하는 코드

for i in news_info:
    news_info[i] = news_info[i].replace("\n","")
    news_info[i] = news_info[i].replace("\\'", "")

출력결과

딕셔너리의 형태로 저장된 것을 볼 수 있습니다.

728x90
반응형