Showing
3 changed files
with
161 additions
and
51 deletions
naverNews/main.py
0 → 100644
1 | +{ | ||
2 | + "cells": [ | ||
3 | + { | ||
4 | + "cell_type": "code", | ||
5 | + "execution_count": 2, | ||
6 | + "metadata": {}, | ||
7 | + "outputs": [ | ||
8 | + { | ||
9 | + "name": "stdout", | ||
10 | + "output_type": "stream", | ||
11 | + "text": [ | ||
12 | + "******************************\n", | ||
13 | + "\n", | ||
14 | + "\n", | ||
15 | + "***< Naver News Crawling >****\n", | ||
16 | + "\n", | ||
17 | + "\n", | ||
18 | + "******************************\n", | ||
19 | + "검색하고자 하는 url을 입력해주세요: https://entertain.naver.com/ranking/comment/list?oid=144&aid=0000642175\n", | ||
20 | + "comment_list를 가져오는 중.....\n", | ||
21 | + "Message: element not interactable\n", | ||
22 | + " (Session info: chrome=78.0.3904.97)\n", | ||
23 | + "\n", | ||
24 | + "[{'userID': 'ydja****', 'comment': '옹벤져스 너무웃겨', 'time': '6일 전'}, {'userID': 'kims****', 'comment': '사랑해요 옹벤져스! 준기엄마 다리 찢을 때 웃겨죽는 줄 진짜 츤데레언니들', 'time': '6일 전'}, {'userID': 'hoho****', 'comment': '옹벤져스가 다른 마을 살인마 잡는 이야기로 시즌 2. 갑시다', 'time': '6일 전'}]\n", | ||
25 | + "comment_list를 다 가져왔습니다!\n" | ||
26 | + ] | ||
27 | + } | ||
28 | + ], | ||
29 | + "source": [ | ||
30 | + "import naverNews_crawling \n", | ||
31 | + "from time import sleep\n", | ||
32 | + "\n", | ||
33 | + "def print_cList(c_List) :\n", | ||
34 | + " for item in c_List :\n", | ||
35 | + " print(item)\n", | ||
36 | + "\n", | ||
37 | + "def search_by_author(c_List,user_ID) :\n", | ||
38 | + " result_List = []\n", | ||
39 | + " for item in c_List :\n", | ||
40 | + " print(item['userID'])\n", | ||
41 | + " if ( user_ID in item['userID']) :\n", | ||
42 | + " result_List.append(item)\n", | ||
43 | + " return result_List\n", | ||
44 | + "\n", | ||
45 | + "def search_by_keyword(c_List,keyword) :\n", | ||
46 | + " result_List = []\n", | ||
47 | + " for item in c_List :\n", | ||
48 | + " print(item['comment'])\n", | ||
49 | + " if ( keyword in item['comment']) :\n", | ||
50 | + " result_List.append(item)\n", | ||
51 | + " return result_List\n", | ||
52 | + " \n", | ||
53 | + "'''\n", | ||
54 | + "def search_by_time(c_List,_time) :\n", | ||
55 | + " result_List = []\n", | ||
56 | + " for item in c_List :\n", | ||
57 | + " print(item['time'])\n", | ||
58 | + " if ( keyword in item['comment']) :\n", | ||
59 | + " result_List.append(item)\n", | ||
60 | + " return result_List \n", | ||
61 | + " \n", | ||
62 | + "''' \n", | ||
63 | + "\n", | ||
64 | + "def main ():\n", | ||
65 | + " ## 시작화면\n", | ||
66 | + " \n", | ||
67 | + " _star = '*'\n", | ||
68 | + " print(_star.center(30,'*'))\n", | ||
69 | + " print('\\n')\n", | ||
70 | + " headString = '< Naver News Crawling >'\n", | ||
71 | + " print(headString.center(30,'*'))\n", | ||
72 | + " print('\\n')\n", | ||
73 | + " print(_star.center(30,'*'))\n", | ||
74 | + " \n", | ||
75 | + " \n", | ||
76 | + " # 검색하고자 하는 url을 입력받는다\n", | ||
77 | + " _url = input('검색하고자 하는 url을 입력해주세요: ')\n", | ||
78 | + " print('comment_list를 가져오는 중.....')\n", | ||
79 | + " cList = naverNews_crawling.getData(_url)\n", | ||
80 | + " print('comment_list를 다 가져왔습니다!')\n", | ||
81 | + "\n", | ||
82 | + "main()" | ||
83 | + ] | ||
84 | + } | ||
85 | + ], | ||
86 | + "metadata": { | ||
87 | + "kernelspec": { | ||
88 | + "display_name": "Python 3", | ||
89 | + "language": "python", | ||
90 | + "name": "python3" | ||
91 | + }, | ||
92 | + "language_info": { | ||
93 | + "codemirror_mode": { | ||
94 | + "name": "ipython", | ||
95 | + "version": 3 | ||
96 | + }, | ||
97 | + "file_extension": ".py", | ||
98 | + "mimetype": "text/x-python", | ||
99 | + "name": "python", | ||
100 | + "nbconvert_exporter": "python", | ||
101 | + "pygments_lexer": "ipython3", | ||
102 | + "version": "3.7.3" | ||
103 | + } | ||
104 | + }, | ||
105 | + "nbformat": 4, | ||
106 | + "nbformat_minor": 2 | ||
107 | +} |
1 | 1. Data 받아오기 | 1 | 1. Data 받아오기 |
2 | 1) selenuim을 이용하여 웹페이지에서 데이터를 검색 | 2 | 1) selenuim을 이용하여 웹페이지에서 데이터를 검색 |
3 | - 2) 원하는 URL 입력받음(구현예정) | 3 | + 2) 원하는 URL 입력받는다 |
4 | 3) headless하게 구현하기 위해 chrome option 적용하여 driver 생성 | 4 | 3) headless하게 구현하기 위해 chrome option 적용하여 driver 생성 |
5 | 4) naverNews는 댓글 영역 하단 부 '더보기'를 지속적으로 눌러줘야하므로 | 5 | 4) naverNews는 댓글 영역 하단 부 '더보기'를 지속적으로 눌러줘야하므로 |
6 | driver의 find_element_by_css_selector함수로 해당 class인 | 6 | driver의 find_element_by_css_selector함수로 해당 class인 |
... | @@ -13,9 +13,15 @@ | ... | @@ -13,9 +13,15 @@ |
13 | 3) 저장된 dictionary list(info_dic)을 최종 결과 리스트인 naverNewsList에 저장한다. | 13 | 3) 저장된 dictionary list(info_dic)을 최종 결과 리스트인 naverNewsList에 저장한다. |
14 | 14 | ||
15 | 3. 함수 구현 | 15 | 3. 함수 구현 |
16 | - 위에서 받아온 데이터를 바탕으로 기능 구현 예정 | ||
17 | 1) KEYWORD 기반 검색 기능 | 16 | 1) KEYWORD 기반 검색 기능 |
18 | 2) 가장 자주 나온 단어 검색 기능 | 17 | 2) 가장 자주 나온 단어 검색 기능 |
19 | 3) ID 기반 검색 기능 | 18 | 3) ID 기반 검색 기능 |
20 | 4) 시간 대별 검색 기능 | 19 | 4) 시간 대별 검색 기능 |
21 | - 등 여러 함수 구현 예정 | ||
... | \ No newline at end of file | ... | \ No newline at end of file |
20 | + 등 여러 함수 구현 예정 | ||
21 | + | ||
22 | +=> 수정사항 | ||
23 | + | ||
24 | + data를 get하여 정제하는 파일을 모듈로 분리해 내어 list형태로 저장된 데이터셋을 반환하여 | ||
25 | + main 에서 사용할 수 있도록 한다. 이 후 main에서 리스트를 받아와 url을 입력받아 데이터를 | ||
26 | + 받아오는 방식으로 사용한다. 이 후, keyword기반, id기반, 시간대 기반 검색 함수를 구현하였고 | ||
27 | + 시간대별 검색 함수의 기능 보강과 가장 자주 나온 단어 검색 기능을 추가 구현할 예정이다. | ||
... | \ No newline at end of file | ... | \ No newline at end of file | ... | ... |
... | @@ -3,54 +3,51 @@ from selenium.common import exceptions | ... | @@ -3,54 +3,51 @@ from selenium.common import exceptions |
3 | from bs4 import BeautifulSoup | 3 | from bs4 import BeautifulSoup |
4 | import time | 4 | import time |
5 | 5 | ||
6 | -## chrome option걸기 (headless하게 웹 크롤링 수행하기 위해<웹페이지 안보이게 하기>) | 6 | +def getData(url): |
7 | - | 7 | + ## chrome option걸기 (headless하게 웹 크롤링 수행하기 위해<웹페이지 안보이게 하기>) |
8 | -options = webdriver.ChromeOptions() | 8 | + options = webdriver.ChromeOptions() |
9 | -#options.add_argument('headless') | 9 | + #options.add_argument('headless') |
10 | -#options.add_argument("disable-gpu") | 10 | + #options.add_argument("disable-gpu") |
11 | - | 11 | + #_url = "https://entertain.naver.com/ranking/comment/list?oid=144&aid=0000642175" # 크롤링할 URL |
12 | -_url = "https://entertain.naver.com/ranking/comment/list?oid=144&aid=0000642175" # 크롤링할 URL | 12 | + _url = url # 크롤링할 URL |
13 | -webDriver = "C:\\Users\\user\\Desktop\\chromedriver_win32\\chromedriver.exe" # 내 웹드라이버 위치 | 13 | + webDriver = "C:\\Users\\user\\Desktop\\chromedriver_win32\\chromedriver.exe" # 내 웹드라이버 위치 |
14 | - | 14 | + driver = webdriver.Chrome(webDriver,chrome_options=options) |
15 | - | 15 | + #driver = webdriver.Chrome(webDriver) |
16 | -driver = webdriver.Chrome(webDriver,chrome_options=options) | 16 | + driver.get(_url) |
17 | -#driver = webdriver.Chrome(webDriver) | 17 | + pageCnt = 0 |
18 | -driver.get(_url) | 18 | + driver.implicitly_wait(3) # 페이지가 다 로드 될때까지 기다리게함 |
19 | - | 19 | + try: |
20 | -pageCnt = 0 | 20 | + while True: # 댓글 페이지 끝날때까지 돌림 |
21 | - | 21 | + #driver의 find_element_by_css_selector함수로 '네이버 뉴스'의 댓글 '더보기' 버튼을 찾아서 계속 클릭해준다(끝까지) |
22 | -driver.implicitly_wait(3) # 페이지가 다 로드 될때까지 기다리게함 | 22 | + driver.find_element_by_css_selector(".u_cbox_btn_more").click() |
23 | - | 23 | + pageCnt = pageCnt+1 |
24 | -try: | 24 | + |
25 | - while True: # 댓글 페이지 끝날때까지 돌림 | 25 | + except exceptions.ElementNotVisibleException as e: # 페이지가 끝남 |
26 | - #driver의 find_element_by_css_selector함수로 '네이버 뉴스'의 댓글 '더보기' 버튼을 찾아서 계속 클릭해준다(끝까지) | 26 | + pass |
27 | - driver.find_element_by_css_selector(".u_cbox_btn_more").click() | 27 | + |
28 | - pageCnt = pageCnt+1 | 28 | + except Exception as e: # 다른 예외 발생시 확인 |
29 | + print(e) | ||
29 | 30 | ||
30 | -except exceptions.ElementNotVisibleException as e: # 페이지가 끝남 | 31 | + pageSource = driver.page_source # 페이지 소스를 따와서 |
31 | - pass | 32 | + result = BeautifulSoup(pageSource, "lxml") # 빠르게 뽑아오기 위해 lxml 사용 |
33 | + | ||
34 | + # nickname, text, time을 raw하게 뽑아온다 | ||
35 | + comments_raw = result.find_all("span", {"class" : "u_cbox_contents"}) | ||
36 | + nicknames_raw = result.find_all("span", {"class" : "u_cbox_nick"}) | ||
37 | + times_raw = result.find_all("span", {"class" : "u_cbox_date"}) | ||
38 | + | ||
39 | + # nickname, text, time 값 만을 뽑아내어 리스트로 정리한다 | ||
40 | + comments = [comment.text for comment in comments_raw] | ||
41 | + nicknames = [nickname.text for nickname in nicknames_raw] | ||
42 | + times = [time.text for time in times_raw] | ||
32 | 43 | ||
33 | -except Exception as e: # 다른 예외 발생시 확인 | 44 | + naverNewsList = [] |
34 | - print(e) | ||
35 | 45 | ||
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 |
46 | + for i in range(len(comments)): | ||
47 | + info_dic = {'userID' : nicknames[i], 'comment' : comments[i], 'time' : times[i]} | ||
48 | + naverNewsList.append(info_dic) | ||
49 | + | ||
50 | + print(naverNewsList[:3]) | ||
51 | + | ||
52 | + return naverNewsList | ||
53 | + #driver.quit() | ||
... | \ No newline at end of file | ... | \ No newline at end of file | ... | ... |
-
Please register or login to post a comment