장준영

naverNews의 댓글관련 정보수집 구현

1 +1. Data 받아오기
2 + 1) selenuim을 이용하여 웹페이지에서 데이터를 검색
3 + 2) 원하는 URL 입력받음(구현예정)
4 + 3) headless하게 구현하기 위해 chrome option 적용하여 driver 생성
5 + 4) naverNews는 댓글 영역 하단 부 '더보기'를 지속적으로 눌러줘야하므로
6 + driver의 find_element_by_css_selector함수로 해당 class인
7 + u_cbox_btn_more을 페이지가 끝날 때까지 돌림
8 + 5) 위의 과정에서 얻은 페이지 소스를 beautifulSoup을 이용하여, find_all을 통해 {사용자ID, 댓글, 작성시간}의 데이터를 각각 raw하게 뽑음. (naverNews의 제한적인 특징으로 사용자ID 뒤 4자리는 비공개처리됨)
9 +
10 +2. 사용할 DataSet으로 가공
11 + 1) 리스트 형태로 각각 nicknames(사용자ID), comments(댓글), times(작성시간)을 뽑아냄
12 + 2) 세 리스트에서 짝을 이루는 쌍을 dictionary형태로 {사용자ID, 댓글, 작성시간} 다음과 같이 저장
13 + 3) 저장된 dictionary list(info_dic)을 최종 결과 리스트인 naverNewsList에 저장한다.
14 +
15 +3. 함수 구현
16 + 위에서 받아온 데이터를 바탕으로 기능 구현 예정
17 + 1) KEYWORD 기반 검색 기능
18 + 2) 가장 자주 나온 단어 검색 기능
19 + 3) ID 기반 검색 기능
20 + 4) 시간 대별 검색 기능
21 + 등 여러 함수 구현 예정
...\ No newline at end of file ...\ No newline at end of file
1 +from selenium import webdriver
2 +from selenium.common import exceptions
3 +from bs4 import BeautifulSoup
4 +import time
5 +
6 +## chrome option걸기 (headless하게 웹 크롤링 수행하기 위해<웹페이지 안보이게 하기>)
7 +
8 +options = webdriver.ChromeOptions()
9 +#options.add_argument('headless')
10 +#options.add_argument("disable-gpu")
11 +
12 +_url = "https://entertain.naver.com/ranking/comment/list?oid=144&aid=0000642175" # 크롤링할 URL
13 +webDriver = "C:\\Users\\user\\Desktop\\chromedriver_win32\\chromedriver.exe" # 내 웹드라이버 위치
14 +
15 +
16 +driver = webdriver.Chrome(webDriver,chrome_options=options)
17 +#driver = webdriver.Chrome(webDriver)
18 +driver.get(_url)
19 +
20 +pageCnt = 0
21 +
22 +driver.implicitly_wait(3) # 페이지가 다 로드 될때까지 기다리게함
23 +
24 +try:
25 + while True: # 댓글 페이지 끝날때까지 돌림
26 + #driver의 find_element_by_css_selector함수로 '네이버 뉴스'의 댓글 '더보기' 버튼을 찾아서 계속 클릭해준다(끝까지)
27 + driver.find_element_by_css_selector(".u_cbox_btn_more").click()
28 + pageCnt = pageCnt+1
29 +
30 +except exceptions.ElementNotVisibleException as e: # 페이지가 끝남
31 + pass
32 +
33 +except Exception as e: # 다른 예외 발생시 확인
34 + print(e)
35 +
36 +pageSource = driver.page_source # 페이지 소스를 따와서
37 +result = BeautifulSoup(pageSource, "lxml") # 빠르게 뽑아오기 위해 lxml 사용
38 +
39 +# nickname, text, time을 raw하게 뽑아온다
40 +comments_raw = result.find_all("span", {"class" : "u_cbox_contents"})
41 +nicknames_raw = result.find_all("span", {"class" : "u_cbox_nick"})
42 +times_raw = result.find_all("span", {"class" : "u_cbox_date"})
43 +
44 +# nickname, text, time 값 만을 뽑아내어 리스트로 정리한다
45 +comments = [comment.text for comment in comments_raw]
46 +nicknames = [nickname.text for nickname in nicknames_raw]
47 +times = [time.text for time in times_raw]
48 +
49 +naverNewsList = []
50 +
51 +for i in range(len(comments)):
52 + info_dic = {'userID' : nicknames[i], 'comment' : comments[i], 'time' : times[i]}
53 + naverNewsList.append(info_dic)
54 +
55 +print(naverNewsList[:3])
56 +#driver.quit()
...\ No newline at end of file ...\ No newline at end of file