빅데이터/Selenium
Selenium 기초 및 활용 하기 5-2 - 네이버 뉴스 댓글 스크래핑
H-V
2022. 1. 12. 18:25
유투버 '이수안컴퓨터연구소' 강의 참조
- 현재까지 1개의 뉴스 + 그 뉴스의 관련 댓글을 잘 가져 온다.
- 추가로 특정 키워드를 검색해서 나오는 뉴스들 + 그와 관련된 댓글을 가져와보도록 하자
- 검색 돋보기 버튼을 눌러 이동되는 페이지의 URL를 가지고 진행
- 간단히 '네이버 뉴스' 만 들고와서 할 예정. 즉 검색 페이지는 유지하면서 네이버 뉴스 탭을 따로 띄워서 스크래핑 하는 방식
01 탭 / URL 세팅
def scraping():
wd = webdriver.Chrome('chromedriver', options=chrome_options)
wd.implicitly_wait(3) #대기 시간
wd.execute_script('window.open("about:blank", "_blank");') #JS의 새 탭을 띄우는 용도
tabs = wd.window_handles #탭 핸들링이 가능해 짐
wd.switch_to.window(tabs[0]) #첫번째 탭으로 전환
query = input("검색어 입력: ")
search_url = "https://search.naver.com/search.naver?where=news&ie=utf8&sm=nws_hty&query=" + query
wd.get(search_url)
...
02 검색된 창에서 '네이버 뉴스' 만 스크래핑
def scraping():
wd = webdriver.Chrome('chromedriver', options=chrome_options)
wd.implicitly_wait(3) #대기 시간
# --- 검색을 위한 세팅 ---
wd.execute_script('window.open("about:blank", "_blank");') #JS의 새 탭을 띄우는 용도
tabs = wd.window_handles #탭 핸들링이 가능해 짐
wd.switch_to.window(tabs[0]) #첫번째 탭으로 전환
query = input("검색어 입력: ")
search_url = "https://search.naver.com/search.naver?where=news&ie=utf8&sm=nws_hty&query=" + query
wd.get(search_url)
# --- Data-Frame ---
news_idx = 0
news_df = pd.DataFrame(columns=("Title","Press","DateTime","Article","Good","Warm","Sad","Angry","Want","Recommend","URL"))
comments_df = pd.DataFrame()
# -- 검색 이후 '네이버 뉴스' 만 스크래핑 ---
while True:
info_list = wd.find_elements(By.CLASS_NAME, 'info_group')
for info in info_list:
try:
first_step = info.find_elements(By.TAG_NAME, 'a')
news_url = first_step[1].get_attribute('href') #'네이버 뉴스' 의 링크를 가져 옴
# print(news_url)
except:
continue
wd.switch_to.window(tabs[1])
wd.get(news_url)
news_df.loc[news_idx] = news_scraping(news_url, wd)
news_idx += 1
# --- 코멘트를 PD로 만들고 계속 합쳐서 만듬 ---
df = comments_scraping(news_url, wd)
comments_df = pd.concat([comments_df, df])
wd.close()
return news_df, comments_df
03 페이징
def scraping():
...
Whie True:
....
# --- 페이징 ---
try:
wd.switch_to.window(tabs[0]) #탭[1]에서 스크래핑이 다 끝나면 다시 텝[0]으로 돌아오고 다음 페이지로 이동 시킴
wd.find_element(By.CLASS_NAME, 'btn_next').click()
time.sleep(1)
except:
break
04 테스트