네이버뉴스 100개 크롤링 + 추가도전

숙제는 힌트 주신 그대로 이어 붙이니 실패없이 바로 csv 파일로 출력이 잘 되었습니다

검색어는 “전기차”로 하였어요.

여기서 추가적인 주문을 해보았습니다.

“결과가 만족스럽게 나왔어. 여기서 뉴스의 링크를 하이퍼링크로 만들어서 링크를 클릭할 때 바로 그 뉴스로 연결되게 하고 싶어”

바로 하이퍼링크를 연결시켜주는 코드가 완성되었습니다. 하지만 이번에는 csv 파일 확인없이 바로 추가적인 주문을 했어요.

“이 코드를 VS code로만 구동하는 것은 재미가 없어. 이것을 어떤 툴로 앱처럼 만들어서 바로 예쁘게 검색어를 입력하고 그 화면에서 바로 title과 링크를 보여주는 화면을 구성하고 싶어. 어떤 툴을 추가로 사용하면 될까?”

그러니 이것저것 추천을 하면서 가장 쉬운 “streamlit”을 써보라고 합니다.

“To turn this script into an interactive and visually appealing app, you can use a framework that allows for building desktop applications. A popular choice for this purpose is PyQt or Tkinter for desktop apps, and Streamlit or Dash for web apps. Here, I'll guide you through using Streamlit, which is simple to use and allows you to create a web app with an interactive UI.”

이후 이것저것 실패가 몇번 있었는데, 최종 산출물이 이렇게 나오네요.

import streamlit as st

from bs4 import BeautifulSoup

import requests

import time

from datetime import datetime

base_url = "https://search.naver.com/search.naver?ssc=tab.news.all&where=news&sm=tab_jum&query="

# Streamlit UI components

st.title("Naver News Scraper")

keyword = st.text_input("검색어를 입력하세요:")

max_articles = st.slider("최대 뉴스 기사 수:", 10, 100, 50)

if st.button("검색"):

if keyword:

search_url = base_url + keyword

# 크롤링한 뉴스 기사 리스트

articles = []

page = 1

while len(articles) < max_articles:

url = search_url + "&start=" + str(page)

response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')

news_list = soup.select('a.news_tit')

for news in news_list:

title = news.get('title')

link = news.get('href')

articles.append({'Title': title, 'Link': link})

if len(articles) >= max_articles:

break

page += 10 # 네이버 뉴스 검색 결과 페이지는 10개 단위로 넘어감

time.sleep(1) # 웹 서버에 과부하를 주지 않기 위해 잠시 대기

st.write("뉴스 기사 목록:")

for article in articles:

st.markdown(f"[{article['Title']}]({article['Link']})")

else:

st.error("검색어를 입력하세요!")

그리고 Terminal에서 다음 명령어 실행: streamlit run app.py

Chrome browser가 열리면서 이런 화면이 뜨네요.


검색어: 동일하게 “전기차”
최대 뉴스기사수는 저걸로 조절하나봅니다.
PC 부하를 줄이기 위해 애매하게 16개로 설정하여 검색 클릭.



진짜 16개가 크롤링되어 나옵니다.

하이퍼링크 눌러보니 기사로 연결도 잘되네요.

끝.

2
1개의 답글

👉 이 게시글도 읽어보세요