https://comibird.tistory.com/6
[파이썬] pandas 를 이용한 웹 크롤링 - 1
인터넷에서 원하는 데이터를 수집하는 것을 웹 크롤링이라고 한다. 다양한 방법 중 python 언어를 이용하여 selenium과 BeautifulSoup를 통해 크롤링하는 방법을 소개한다. 1. Selenium은 웹 드라이버를 실
comibird.tistory.com
이전 글에서 검색 후 View탭 까지 가는 것을 구현했다.
이번에는 View탭에서 데이터를 외부 파일에 저장하는 것까지 구현해보겠다.
또한 기본 상태에서는 검색 후 스크롤을 하지 않아 적은 양의 데이터만 추출하기 때문에 스크롤도 구현하여 원하는 양의 데이터를 추출해보겠다.
구현 방법
우선 구현할 코드 전문이다.
#0 네이버 웹사이트 제어하기
from selenium import webdriver
from bs4 import BeautifulSoup
import os, sys, time, math
#1 검색어 입력과 웹페이지 열기
q_txt = input("검색어는 : ")
s_date = input("시작 날짜 : ")
e_date = input("종료 날짜 : ")
chrome_path = "c:/workspace/py_temp/chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
#2 웹사이트 접속하기
time.sleep(2)
driver.get("https://search.naver.com/search.naver?where=blog&query=" + q_txt
+"&nso=so:r,p:from"+s_date+"to"+e_date)
time.sleep(2)
driver.maximize_window()
# 팝업닫기(참고)
# driver.switch_to_window(driver.window_handles[1]) // 팝업창으로 넘어가기
# driver.close() // 팝업창 닫기
# driver.switch_to_window(driver.window_handles[0]) // 원래 홈페이지로 돌아오기
#3 자동 스크롤 다운 함수
def scroll_down(driver):
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
time.sleep(3)
page_cnt = 5
i = 1
while (i<=page_cnt):
scroll_down(driver)
i += 1
#4 데이터 수집하기
soup = BeautifulSoup(driver.page_source, 'html.parser')
content = soup.find('ul', class_="lst_total").find_all('li')
for i in content :
print(i.get_text().replace("\n","").replace("문서 저장하기 Keep에 저장 Keep 바로가기","").lstrip())
print("\n")
#5 표준출력방향 전환하여 저장하기
orig_out = sys.stdout
f_name = open("C:\workspace\py_temp/naver.txt",'a',encoding = "UTF-8")
sys.stdout = f_name
for i in content :
print(i.get_text().replace("\n","").replace("문서 저장하기 Keep에 저장 Keep 바로가기","").lstrip())
print("\n")
f_name.close()
sys.stdout = orig_out
time.sleep(1)
driver.close()
1. 자동 스크롤 다운 함수를 구현해본다.
scroll_down()은 문서의 높이만큼 스크롤을 처음부터 끝까지 한번 해주는 함수이다.
while 문으로 함수를 5번 반복하여 5번 스크롤하도록 구현하여 스크롤 데이터 양을 늘려준다.
#3 자동 스크롤 다운 함수
def scroll_down(driver):
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
time.sleep(3)
page_cnt = 5
i = 1
while (i<=page_cnt):
scroll_down(driver)
i += 1
2. 데이터를 수집한다.
soup는 html 코드에서 원하는 부분만 골라내는 모듈이다. html.parser를 통해 html을 가져오고 'li'라는 태그를 찾아
content에 넣는다.
이 상태로 데이터를 가져오면 "문서 저장하기 keep에 저장 keep 바로가기"라는 문구가 중복해서 출력되는 것을 확일할 수 있다. 따라서 replace(문구를 대체해준다)와 lstrip(왼쪽의 공백을 제거한다.)를 적절히 이용하여 데이터를 가공해준다.
#4 데이터 수집하기
soup = BeautifulSoup(driver.page_source, 'html.parser')
content = soup.find('ul', class_="lst_total").find_all('li')
for i in content :
print(i.get_text().replace("\n","").replace("문서 저장하기 Keep에 저장 Keep 바로가기","").lstrip())
print("\n")
출력 결과
3. 외부 파일로 저장한다.
위에서 크롤링해온 데이터를 외부 text 파일에 넣어본다.
파일을 os 모듈을 통해 파일을 열어, 크롤링 후 print 되는 데이터들을 text파일 안에 append 하도록 설정한다.
그리고 파일을 닫고 driver를 닫아 웹페이지를 닫아준다.
#5 표준출력방향 전환하여 저장하기
orig_out = sys.stdout
f_name = open("C:\workspace\py_temp/naver.txt",'a',encoding = "UTF-8")
sys.stdout = f_name
for i in content :
print(i.get_text().replace("\n","").replace("문서 저장하기 Keep에 저장 Keep 바로가기","").lstrip())
print("\n")
f_name.close()
sys.stdout = orig_out
time.sleep(1)
driver.close()
외부 파일 naver.txt 에 잘 저장됐다.