1. 이번주에 배운 코드 중 아래 함수 수행한 결과화면
2.
f = open("c:\\data\\foo.txt", 'w', encoding = "utf8")
f.write(content_list)
f.close()
f = open("내려받을 파일 경로 및 파일명", 'w', encoding = "utf8") <- 오류나면 인코딩 써주고 없으면 안써도 됨.
f.write(데이터 담긴 변수명)
f.close()
------------------------------------------------------------------------------------
#1. 필요한 패키지들을 불러옵니다
from selenium import webdriver
from konlpy.tag import Okt
from nltk import Text
from matplotlib import font_manager, rc
from wordcloud import WordCloud
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import matplotlib.pyplot as plt
import time
#2. 크롬 드라이버의 위치를 지정합니다
path = "C:\\data\\chromedriver.exe" # 웹드라이버 실행
driver = webdriver.Chrome(path) # 드라이버 경로 설정
#3. 필요한 변수와 검색어를 준비합니다.
url_list = [] # 블로그 url을 저장하기 위한 변수
content_list = "" # 블로그 content를 누적하기 위한 변수
text = "비빔면" # 검색어
#4. 블러그 url 수집 코드
for i in range(1, 101): # 1~100 페이지까지의 블로그 내용을 읽어옴
url = ' https://section.blog.naver.com/Search/Post.nhn?pageNo='+ str(i) + '&rangeType=ALL&orderBy=sim&keyword=' + text # url 값 설정
driver.get(url)
time.sleep(0.5) # 오류 방지 sleep
for j in range(1, 8): # 1페이지에 7개씩의 블러그가 있으므로
titles = driver.find_element(By.XPATH,'/html/body/ui-view/div/main/div/div/section/div[2]/div['+str(j)+']/div/div[1]/div[1]/a[1]')
title = titles.get_attribute('href')
url_list.append(title)
print("url 수집 끝, 해당 url 데이터 크롤링")
#5. 블러그 url 로 접속해서 본문 텍스트를 가져와 계속 이어 붙이는 코드
for url in url_list: # 저장했던 블로그 하나씩 순회
driver.get(url)
driver.switch_to.frame('mainFrame')
overlays = ".se-component.se-text.se-l-default" # 내용 크롤링
contents=driver.find_elements(By.CSS_SELECTOR, overlays)
for content in contents:
content_list = content_list + content.text # 각 블로그의 내용을 변수에 누적함