파이썬으로 네이버 뉴스 본문을 수집하는 방법
네이버에서 검색한 뉴스를 긁어오는 코드입니다. 각 홈페이지로 리다이렉트 되는 기사의 경우 주소의 일관성이 없어서 기사 내용은 불러오지 못 합니다. 그래서 네이버 포털 자체에서 제공하는 뉴스 기사만 대상으로 기사 내용을 포함해서 수집합니다.
자세한 설명은 추후 시간이 날 때 하도록 하겠습니다.
아래는 코드 전문입니다.
불필요한 코드들이 중간에 섞여 있습니다.
전체코드
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import pandas as pd
from datetime import datetime
import os
RESULT_PATH = 'D:/키워드 분석/네이버뉴스(02)/'
now = datetime.now() #파일이름 현 시간으로 저장하기
# %%
# 뉴스 수집을 위한 def입니다.
def get_news(n_url):
news_detail = []
breq = requests.get(n_url)
bsoup = BeautifulSoup(breq.content, 'html.parser')
title = bsoup.select('h3#articleTitle')[0].text.replace('\\\\n', " ") #대괄호는 h3 #articleTitle 인 것중 첫번째 그룹만 가져오겠다.
news_detail.append(title)
pdate = bsoup.select('.t11')[0].get_text()[:11]
news_detail.append(pdate)
_text = bsoup.select('#articleBodyContents')[0].get_text().replace('\\\\n', " ")
btext = _text.replace("// flash 오류를 우회하기 위한 함수 추가 function _flash_removeCallback() {}", "")
news_detail.append(btext.strip())
news_detail.append(n_url)
pcompany = bsoup.select('#footer address')[0].a.get_text()
news_detail.append(pcompany)
return news_detail
def crawler(maxpage,query,s_date,e_date):
s_from = s_date.replace(".","")
e_to = e_date.replace(".","")
page = 1
maxpage_t =(int(maxpage)-1)*10+1 # 11= 2페이지 21=3페이지 31=4페이지 ...81=9페이지 , 91=10페이지, 101=11페이지
f = open("D:/키워드 분석/네이버뉴스(02)/contents_text.txt", 'w', encoding='utf-8')
while page < maxpage_t:
print(page)
url = "<https://search.naver.com/search.naver?where=news&query=>" + query + "&sort=0&ds=" + s_date + "&de=" + e_date + "&nso=so%3Ar%2Cp%3Afrom" + s_from + "to" + e_to + "%2Ca%3A&start=" + str(page)
req = requests.get(url)
print(url)
cont = req.content
soup = BeautifulSoup(cont, 'html.parser')
#print(soup)
for urls in soup.select("._sp_each_url"):
try :
#print(urls["href"])
if urls["href"].startswith("<https://news.naver.com>"):
#print(urls["href"])
news_detail = get_news(urls["href"])
# pdate, pcompany, title, btext
f.write("{}\\\\t{}\\\\t{}\\\\t{}\\\\t{}\\\\n".format(news_detail[1], news_detail[4], news_detail[0], news_detail[2],news_detail[3])) # new style
except Exception as e:
print(e)
continue
page += 10
f.close()
def excel_make():
data = pd.read_csv(RESULT_PATH+'contents_text.txt', sep='\\\\t',header=None, error_bad_lines=False)
data.columns = ['years','company','title','contents','link']
print(data)
xlsx_outputFileName = '%s-%s-%s %s시 %s분 %s초 result.xlsx' % (now.year, now.month, now.day, now.hour, now.minute, now.second)
#xlsx_name = 'result' + '.xlsx'
data.to_excel(RESULT_PATH+xlsx_outputFileName, encoding='utf-8')
def main_mod():
x=0 # 연도별로 반복시키기 위해서(400줄 이상 네이버가 검색 결과를 제공하지 않기 때문에, 400줄 단위로 작업해야 하며, 연도를 나눠야 한다.)
while x<20:
maxpage = 400
query = '"문화영향평가"'
s_date = "20{0:0>2}.01.01".format(x) #2019.01.01
print(s_date)
e_date = "20{0:0>2}.12.31".format(x) #2019.04.28
crawler(maxpage,query,s_date,e_date) #검색된 네이버뉴스의 기사내용을 크롤링합니다.
os.rename("D:/OneDrive - 서울대학교/키워드 분석/네이버뉴스(02)/contents_text.txt", "D:/OneDrive - 서울대학교/키워드 분석/네이버뉴스(02)/contents_{0:0>2}.txt".format(x)) # 2001년도 숫자 x=1을 01로 채우기
x+=1
# %%
main_mod()
# %%
# 경우에 따라 마지막 뉴스가 수백번 중복되는 경우가 발생하여 중복 제거가 필요
x=0 # 0년부터 2019년까지 반복작업
while x<20:
with open('D:/키워드 분석/네이버뉴스(02)/contents_{0:0>2}.txt'.format(x), 'r', encoding='utf-8') as f:
list_file = f.readlines()
list_file = [line.rstrip('\\\\n') for line in list_file]
new_list=list(set(list_file)) # 중복 뉴스기사 제거하기
with open('D:/키워드 분석/네이버뉴스(02)/contents_mod_{0:0>2}.txt'.format(x), 'w', encoding='utf-8') as nf:
for line in new_list:
nf.write(line+'\\\\n')
x+=1
# %%
# 수집한 연도별 데이터 기초통계량(데이터 수집 과정에서 줄바꿈이 제대로 이루어지지 않아, 기사 개수를 세는 것에 오류)
#!/usr/bin/env python3
import csv
import glob
import os
import sys
input_path = "D:/키워드 분석/네이버뉴스(02)"
file_counter = 0
for input_file in glob.glob(os.path.join(input_path,'*contents_mod_*.txt')):
line_counter = 1
with open(input_file, 'r', encoding="utf-8") as txt_in_file:
for line in txt_in_file:
line_counter += 1
print('{0!s}: \\\\t{1:d} rows'.format(os.path.basename(input_file), line_counter))
file_counter += 1
print('Number of files: {0:d}'.format(file_counter))
