검색조건
- 검색어: 데이터과학, 파이썬
- 검색엔지: 네이버
- 검색기간: 최근 6 개월
1-1 네이버 검색창에 데이터과학 파이썬 입력하기
1-2 입력차 아래에 '뉴스' 클릭
1-3 아래 옵션에서 6개월 선택
1-4 마지막으로 모든 선택이 완료된 후에 주소창(url)을 복사해 둔다
1-5 검색 결과 페이지를 넘겨보면 몇 페이지까지 있는지 확인해 봄(여기서는 21 페이지까지 나옴)
- 총 3 개의 코딩 블록으로 구성되어 있음
- 첫 번째는 1-4)에서 복사한 주소를 통하여 검색 결과 페이지를 저장
- 두 번째는 결과 페이지의 내용을 분리해서, 필요한 요소들을 추출
- 세 번째는 추출된 요소들을 데이터 프레임으로 작성
2-1 패키지 로딩
from bs4 import BeautifulSoup
import requests
import openpyxl
from openpyxl import Workbook
import pandas as pd
import numpy as np
from openpyxl.utils.dataframe import dataframe_to_rows
2-2 검색 주소(1-4) 입력
searchPath = "https://search.naver.com/search.naver?where=news&sm=tab_pge&query=%EB%8D%B0%EC%9D%B4%ED%84%B0%EA%B3%BC%ED%95%99%20%ED%8C%8C%EC%9D%B4%EC%8D%AC&sort=0&photo=0&field=0&pd=6&ds=2022.08.04&de=2023.01.31&cluster_rank=52&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:6m,a:all&start="
- 검색주소와 코드에 입력한 검색 주소의 차이
- 웹브라우저에서 복사한 검색 주소 마지막에는 &start = 0 으로 되어 있음
- 입력 코드의 검색 주소는 마지막 0을 뺀 $start = 까지만 입력함
- 왜냐면, $start = 다음이 오는 숫자에 따라서 패이지가 넘어가기 때문임
- 실습 $start = 뒤에 0, 11, 21, 31 을 차례로 입력하고 주소창에 붙여넣어보면 페이지가 넘어가는 것을 알 수 있음
2-3 페이지 번호 리스트 작성
- 총 21페이지까지 있음
- 따라서 $start = 뒤에 0, 11, 21, ... , 201까지 입력하면 됨
- 한 페이지당 10개의 검색결과가 있다. 그래서 다음 패이지로 넘어가면 11이 됨
pageCount = [i if i == 0 else i * 10 + 1 for i in range(21)]
print(pageCount)
[0, 11, 21, 31, 41, 51, 61, 71, 81, 91, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 201]
2-4 웹 페이지 크롤링 하기
- 크롤링하면 화면에 보여지는 전체 페이지가 추출됨
- 전체 페이지에서 뉴스 부분만 추출해야 함
- 뉴스 부분이 위치한 테그는 'div.news_area'임
웹 페이지 구조 보기
검색 결과 창
- div.news_area 에서 div 는 태그 이름이고 news_area는 class 이름
resp = requests.get(f'{searchPath}{pageCount[0]}')
html = resp.text
soup = BeautifulSoup(html, 'html.parser')
totalNews= soup.select('div.news_area')
totalNews[0]
totalNews[0]
2-5 각 뉴스별 상세 페이지 주소 가져오기
m = totalNews[0]
print(m.select_one('a.news_tit'))
url = m.select_one('a.news_tit')['href']
url
2-6 각 뉴스별 제목 가져오기
print(m.select_one('a.news_tit'))
title = m.select_one('a.news_tit').text
title
2-7 짧은 내용 가져오기
print(m.select_one('div.dsc_wrap'))
message = m.select_one('div.dsc_wrap > a.api_txt_lines.dsc_txt_wrap').text
message
2-8 출처 가져오기
press = m.select_one('a.info.press').text
press
2-9 추출한 자료를 데이터 프레임으로 만들기
out = pd.DataFrame(np.array([[date, press, title, message, url]]),
columns=["Date", "Press", "Title", "Message", "URL"])
out
패키지 가져오기
from bs4 import BeautifulSoup
import requests
import openpyxl
from openpyxl import Workbook
import pandas as pd
import numpy as np
from openpyxl.utils.dataframe import dataframe_to_rows
검색 주소, 페이지 리스트 만들기
searchPath = "https://search.naver.com/search.naver?where=news&sm=tab_pge&query=%EB%8D%B0%EC%9D%B4%ED%84%B0%EA%B3%BC%ED%95%99%20%ED%8C%8C%EC%9D%B4%EC%8D%AC&sort=0&photo=0&field=0&pd=6&ds=2022.08.04&de=2023.01.31&cluster_rank=52&mynews=0&office_type=0&office_section_code=0&news_office_checked=&nso=so:r,p:6m,a:all&start="
pageCount = [i if i == 0 else i * 10 + 1 for i in range(21)]
데이터를 저장할 빈 객체 생성
dat = pd.DataFrame()
웹크롤링 및 데이터 저장
for i in range(len(pageCount)):
resp = requests.get(f'{searchPath}{pageCount[i]}')
html = resp.text
soup = BeautifulSoup(html, 'html.parser')
totalNews= soup.select('div.news_area')
for j in range(len(totalNews)):
m = totalNews[j]
url = m.select_one('a.news_tit')['href']
title = m.select_one('a.news_tit').text
message = m.select_one('div.dsc_wrap > a.api_txt_lines.dsc_txt_wrap').text
date = m.select_one('span.info').text
press = m.select_one('a.info.press').text
out = pd.DataFrame(np.array([[date, press, title, message, url]]), columns=["Date", "Press", "Title", "Message", "URL"])
dat = dat.append(out)
결과 확인하기
dat.head()
결과 저장하기
dat.to_excel("resultOut.xlsx")
THE END