3 Aug 2018

[Python] 네이버 기사 크롤링 코드


네이버에서 검색되는 특정 기간 동안의 기사들을 언론사 관계 없이 한번에 끌어올 수 있습니다.

실행방법:

(1) 파이썬 IDLE에 아래 코드를 ctrl c+v해서 다른 이름으로 특정 폴더에 저장 후
(2) Windows PowerShell에서 해당 폴더의 경로를 찾아 실행
PowerShell 실행 시 ls 경로 --> python 파일명.py 입력

파이썬 코드:

import requests
from bs4 import BeautifulSoup
import json
import re
import sys
import time, random



def get_news(n_url):
    news_detail = []
    print(n_url)
    breq = requests.get(n_url)
    bsoup = BeautifulSoup(breq.content, 'html.parser')

    title = bsoup.select('h3#articleTitle')[0].text

    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())

    pcompany = bsoup.select('#footer address')[0].a.get_text()

    news_detail.append(pcompany)

    return news_detail

query = "검색키워드"   # url 인코딩 에러는 encoding parse.quote(query)

s_date = "201x.xx.xx"
e_date = "201x.xx.xx"

s_from = s_date.replace(".","")
e_to = e_date.replace(".","")

page = 1

f = open("C:/Users/사용자이름/Desktop/폴더명/" + query + '크롤.txt', 'w', encoding='utf-8')

while page < 1000:

    print(page)

    url = "https://search.naver.com/search.naver?where=news&query=" + query + "&sort=1&ds=" + s_date + "&de=" + e_date + "&nso=so%3Ar%2Cp%3Afrom" + s_from + "to" + e_to + "%2Ca%3A&start=" + str(page)

    #header 추가

    header = {

        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',

    }

    req = requests.get(url,headers=header)

    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("http://news.naver.com"):

                #print(urls["href"])

                news_detail = get_news(urls["href"])

                    # pdate, pcompany, title, btext

                f.write("{}\t{}\t{}\t{}\n".format(news_detail[1], news_detail[3], news_detail[0],

                                                      news_detail[2]))  # new style

        except Exception as e:

            print(e)

            continue

    page += 10

f.close()

No comments

Copyright © 2018 Mid Air by Ahny. Powered by Blogger.