네이버 뉴스 크롤러 github naver_news_crawling_perfect.py

 

======================================

# -*- coding: utf-8 -*-
  import requests
  from bs4 import BeautifulSoup
  import pandas as pd
  from datetime import datetime
   
  '''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  < naver 뉴스 전문 가져오기 >_select 사용
  - 네이버 뉴스만 가져와서 결과값 조금 작음
  - 결과 메모장 저장 -> 엑셀로 저장
   
  '''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  RESULT_PATH = 'D:/python study/beautifulSoup_ws/crawling_result/'
  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 #대괄호는 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:/python study/beautifulSoup_ws/crawling_result/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():
  maxpage = input("최대 출력할 페이지수 입력하시오: ")
  query = input("검색어 입력: ")
  s_date = input("시작날짜 입력(2019.01.01):") #2019.01.01
  e_date = input("끝날짜 입력(2019.04.28):") #2019.04.28
  crawler(maxpage,query,s_date,e_date) #검색된 네이버뉴스의 기사내용을 크롤링합니다.
   
  excel_make() #엑셀로 만들기
  main()

======================================

 

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

[출처] https://github.com/sbomhoo/naver_news_crawling_perfect

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
47 [python] 파이썬 f-string (파이썬 스트링 앞에 f') file 졸리운_곰 2021.07.17 446
46 [Python] 파이썬으로 복리 계산하기 file 졸리운_곰 2021.07.17 562
45 [python, 파이썬] 연습 문제: 복리 이자 계산 졸리운_곰 2021.07.17 925
44 [python] 파이썬 기초 문법 정리 졸리운_곰 2021.05.17 861
43 [python] [GPU]GPU 사용 Python 코드 실행 졸리운_곰 2021.04.21 567
42 [python] 파이썬 스케줄 수행 - schedule, apscheduler file 졸리운_곰 2020.07.26 454
41 파이썬 스크립트 스케줄링하기 file 졸리운_곰 2020.07.26 1011
40 Python Scheduler 만들기(APScheduler) 졸리운_곰 2020.07.26 1089
39 [python] 주피터 노트북에서 패키지 설치 졸리운_곰 2018.12.06 1225
38 Data Structures and Algorithm In python 파이썬으로 자료구조와 알고리즘 : 출처 인터넷 file 졸리운_곰 2018.08.27 514
37 Mastering Basic Algorithms in the Python Language 이북 출처 인터넷 file 졸리운_곰 2018.08.27 629
36 python dev 사용자 입력과 출력 졸리운_곰 2018.03.01 471
35 APScheduler 사용기 file 졸리운_곰 2018.02.09 1070
34 [파이썬, 조각코드] 스케쥴러 만들기. 졸리운_곰 2018.02.09 795
33 Python virtualenv 정리 (Linux/Windows) 졸리운_곰 2018.01.23 486
32 [Python] 코드난독화 file 졸리운_곰 2018.01.19 1001
31 Python - Way to recursively find and replace string in text files 졸리운_곰 2017.08.30 478
30 Python Coding for Minecraft 마인크래프트를 위한 파이썬 프로그래밍 file 졸리운_곰 2017.05.05 1794
29 Atom을 Python 개발 툴로 사용하기 file 졸리운_곰 2017.03.06 938
28 IPython Notebook을 통한 데이터 분석 #3 file 졸리운_곰 2017.03.05 754
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED