네이버 카페 특정 게시판 제목, 본문, 작성자 스크래핑
@ 참고: https://stricky.tistory.com/471
위 블로그를 참고하여, 내가 사용할 수 있도록 코드를 변경하였다.
from selenium import webdriver #웹 브라우저 자동화
from selenium.webdriver.common.by import By #셀레니움 업그레이드로 인한 필요 라이브러리
from bs4 import BeautifulSoup as bs # html 데이터 전처리
import time # 시간 지연
import pandas as pd
import sqlite3
import csv
import re
# 아이디, 비밀번호 변수로 추가
id = '아이디'
pw = '비밀번호'
# chromedriver는 다운로드 후 경로 지정
driver = webdriver.Chrome('./chromedriver')
driver.implicitly_wait(3)
# 로그인 전용 화면
driver.get('https://nid.naver.com/nidlogin.login')
time.sleep(2)
# 이 부분 잘 안 됨. 자동 방지 문구에서 걸림
# 일단 직접 크롬에서 자동완성문구를 입력하여, 로그인 한 상태에서 스크랩핑
# id, pw 입력
driver.find_element(By.NAME,'id').send_keys(id)
time.sleep(2)
driver.find_element(By.NAME ,'pw').send_keys(pw)
time.sleep(2)
# 로그인 버튼 클릭
driver.find_element(By.CSS_SELECTOR, '.btn_login').click()
# ifram
driver.get('스크래핑을 원하는 페이지 url')
time.sleep(3)
driver.switch_to.frame("cafe_main")
# DB 만들기
conn = sqlite3.connect('파일명.db')
# 보통 url에서 페이지 설정할 수 있음
# 스크래핑 원하는 페이지를 직접 입력
addr = "페이지 설정 url"
driver.get(addr)
driver.switch_to.frame('cafe_main')
html = driver.page_source
soup = bs(html, 'html.parser')
a_num_list = soup.findAll("div",{"class":"inner_number"})
a_title_list = soup.findAll("a",{"class":"article"})
a_writer_list = soup.findAll("a",{"class":"m-tcol-c"})
a_regdate_list = soup.findAll("td",{"class":"td_date"})
total_list = []
article_link_list = [] #글 링크
if i == 0:
for a, b, c, d in zip(a_num_list, a_title_list[17:], a_writer_list[17:], a_regdate_list[17:]): # 공지사항 제외(직접 인덱싱)
list = []
list.append(a.text)
list.append(b.text.strip())
list.append(c.text)
list.append(d.text)
total_list.append(list)
article_link_list.append(addr)
else:
for a, b, c, d in zip(a_num_list, a_title_list, a_writer_list, a_regdate_list):
list = []
list.append(a.text)
list.append(b.text.strip())
list.append(c.text)
list.append(d.text)
total_list.append(list)
article_link_list.append(addr)
# 글 스크랩핑
article_list = []
idx_l = []
sub_l = []
name_l = []
for idx, sub, name, date in total_list:
idx_l.append(idx)
sub_l.append(sub)
name_l.append(name)
for i in idx_l:
adrs = '카페url'+ i #카페 url + 게시글 번호
print(adrs)
driver.get(adrs)
time.sleep(2)
driver.switch_to.frame('cafe_main')
html = driver.page_source
soup = bs(html, 'html.parser')
list = soup.find_all("div", {"class":"article_viewer"})
for xx in list:
cont = ''
cont += xx.text.strip()
article_list.append(cont)
data = pd.DataFrame({'게시글번호': idx_l, '제목':sub_l, '작성자':name_l})
df =pd.DataFrame({'본문내용': article_list})
data1 = pd.concat([data, df], axis = 1)
data1.to_sql('테이블명',con=conn, if_exists='append', index=False)
#연결 해제
conn.close()