[python-크롤링] 파이썬으로 네이버 뉴스 수집하기 – 기사내용 포함

·

·

,

네이버에서 검색한 뉴스를 긁어오는 코드입니다. 각 홈페이지로 리다이렉트 되는 기사의 경우 주소의 일관성이 없어서 기사 내용은 불러오지 못 합니다. 그래서 네이버 포털 자체에서 제공하는 뉴스 기사만 대상으로 기사 내용을 포함해서 수집합니다.

자세한 설명은 추후 시간이 날 때 하도록 하겠습니다.

아래는 코드 전문입니다.

불필요한 코드들이 중간에 섞여 있습니다.

전체코드

# -*- 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 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', " ")
    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
    f = open(RESULT_PATH + 'contents_text.txt', 'w', encoding='utf-8')

    while page < maxpage_t:
        print(page)
        url = f'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={page}'
        req = requests.get(url)
        print(url)
        cont = req.content
        soup = BeautifulSoup(cont, 'html.parser')

        for urls in soup.select("._sp_each_url"):
            try:
                if urls["href"].startswith("https://news.naver.com"):
                    news_detail = get_news(urls["href"])
                    f.write(f"{news_detail[1]}\t{news_detail[4]}\t{news_detail[0]}\t{news_detail[2]}\t{news_detail[3]}\n")
            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']
    xlsx_outputFileName = f'{now.year}-{now.month}-{now.day} {now.hour}시 {now.minute}분 {now.second}초 result.xlsx'
    data.to_excel(RESULT_PATH + xlsx_outputFileName, encoding='utf-8')

def main_mod():
    x = 0
    while x < 20:
        maxpage = 400
        query = '"문화영향평가"'
        s_date = f"20{x:0>2}.01.01"
        e_date = f"20{x:0>2}.12.31"
        print(s_date)
        crawler(maxpage, query, s_date, e_date)
        os.rename(f"D:/키워드 분석/네이버뉴스(02)/contents_text.txt", f"D:/키워드 분석/네이버뉴스(02)/contents_{x:0>2}.txt")
        x += 1

main_mod()

x = 0
while x < 20:
    with open(f'D:/키워드 분석/네이버뉴스(02)/contents_{x:0>2}.txt', '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(f'D:/키워드 분석/네이버뉴스(02)/contents_mod_{x:0>2}.txt', 'w', encoding='utf-8') as nf:
        for line in new_list:
            nf.write(line + '\n')
    x += 1

# 수집한 연도별 데이터 기초 통계량
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))

Code language: PHP (php)

댓글 남기기