네이버 키워드 검색 후 기사 텍스트 추출

2024. 6. 30. 19:34정보처리,전산/Python

반응형
import time
st = 3 # 기다림

#1-1 인터넷 오픈
from selenium import webdriver

#pc ver
driver = webdriver.Chrome(service=service)
#colab ver
#driver=webdriver.Chrome('chromedriver',options=options)

time.sleep(st)

#1-2 네이버 접속
driver.get("http://www.naver.com")
time.sleep(st)
#1-3 키워드 검색
greenbox = driver.find_element(By.XPATH,
                               "/html/body/div[2]/div[1]/div/div[3]/div/div/form/fieldset/div/input")

greenbox.send_keys("semiconductor")
search_button = driver.find_element(By.XPATH, "/html/body/div[2]/div[1]/div/div[3]/div/div/form/fieldset/button")
search_button.click()
time.sleep(st)


news_tab = driver.find_element(By.XPATH, "//a[@role='tab' and contains(@href, 'ssc=tab.news.all')]")
# JavaScript로 요소를 클릭할 수 있도록 스크롤하고 클릭
driver.execute_script("arguments[0].scrollIntoView();", news_tab)
time.sleep(1)  # 스크롤이 완료될 때까지 잠시 대기
news_tab.click()
time.sleep(st)

#1-4.검색 후 최신순 뉴스 링크 접속
orderdate=driver.find_element(By.XPATH,"//a[@class='item' and text()='최신순']")
orderdate.click()
time.sleep(st)

# firstarticle=driver.find_element(By.ID,"sp_nws1")
# firstarticle.click()

#1.5. 뉴스 기사를 배열하여 리스트 변수에 답는다.
first_sel=driver.find_element(By.CLASS_NAME,"list_news")
second_sel=first_sel.find_elements(By.TAG_NAME,"li")
news_title_lists=[]
for a in second_sel:
    news_title_lists.append(a.text.replace("\n",""))

print("추출 텍스트는")
print(news_title_lists)
time.sleep(st)

#2-1 만들어진 리스트 변수를 엑셀로 변환한다.
import pandas as pd 
df=pd.DataFrame(news_title_lists)
df.to_excel('sc_test.xlsx')
time.sleep(st)

#3-1 만들어진 리스트 변수의 본문들을 합쳐서 워드 클라우드로 만드는 라이브러리를 만든다
from wordcloud import WordCloud, STOPWORDS
stopwords=set(STOPWORDS) #불BOOL 용어 지정 
wc=WordCloud(font_path='C:/Windows/Fonts/malgun.ttf',stopwords=stopwords) #wordcloud 객체 지정
wc.generate(str(news_title_lists))
wc.to_file('wordcloud_sc.png')

 

워드클라우드 생성

반응형

'정보처리,전산 > Python' 카테고리의 다른 글

코드 실행 동작 속도 측정 implicitly  (0) 2024.06.30
웹크롤링 엔터키 적용  (0) 2024.06.30
Python Library  (0) 2024.06.30
클래스 인스턴스 생성  (0) 2024.06.29
map  (0) 2024.06.29