1. 검색할 언론사 선택

import sys, os
import requests
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
import requests
from pandas import DataFrame
from bs4 import BeautifulSoup
import re
from datetime import datetime
import pickle, progressbar, json, glob, time
from tqdm import tqdm


from selenium.webdriver.common.keys import Keys
from time import sleep, strftime


###### 날짜 저장 ##########
date = str(datetime.now())
date = date[:date.rfind(':')].replace(' ', '_')
date = date.replace(':','시') + '분'

sleep_sec = 0.5


####### 언론사별 본문 위치 태그 파싱 함수 ###########
print('본문 크롤링에 필요한 함수를 로딩하고 있습니다...\n' + '-' * 100)
def crawling_main_text(url):

    req = requests.get(url)
    req.encoding = None
    soup = BeautifulSoup(req.text, 'html.parser')
    
    # 연합뉴스
    if ('://yna' in url) | ('app.yonhapnews' in url): 
        main_article = soup.find('div', {'class':'story-news article'})
        if main_article == None:
            main_article = soup.find('div', {'class' : 'article-txt'})
            
        text = main_article.text
        
    # MBC 
    elif '//imnews.imbc' in url: 
        text = soup.find('div', {'itemprop' : 'articleBody'}).text
        
    # 매일경제(미라클), req.encoding = None 설정 필요
    elif 'mirakle.mk' in url:
        text = soup.find('div', {'class' : 'view_txt'}).text
        
    # 매일경제, req.encoding = None 설정 필요
    elif 'mk.co' in url:
        text = soup.find('div', {'class' : 'art_txt'}).text
        
    # SBS
    elif 'news.sbs' in url:
        text = soup.find('div', {'itemprop' : 'articleBody'}).text
    
    # KBS
    elif 'news.kbs' in url:
        text = soup.find('div', {'id' : 'cont_newstext'}).text
        
    # JTBC
    elif 'news.jtbc' in url:
        text = soup.find('div', {'class' : 'article_content'}).text
        
    # 그 외
    else:
        text == None
        
    return text.replace('\n','').replace('\r','').replace('<br>','').replace('\t','')
    
    
press_nm = 'KBS'

print('검색할 언론사 : {}'.format(press_nm))

Out[1] :

본문 크롤링에 필요한 함수를 로딩하고 있습니다...
----------------------------------------------------------------------------------------------------
검색할 언론사 : KBS

 

 

2. 키워드 입력

############### 브라우저를 켜고 검색 키워드 입력 ####################
query = '푸바오'
news_num = 10


print('\n' + '=' * 100 + '\n')

print('브라우저를 실행시킵니다(자동 제어)\n')
chrome_path = r'C:\file\chromedriver.exe'
browser = webdriver.Chrome(chrome_path)

news_url = 'https://search.naver.com/search.naver?where=news&query={}'.format(query)
browser.get(news_url)
time.sleep(sleep_sec)

검색어는 '푸바오'이고 10개의 기사를 추출하도록 설정하였다.

 

 

3. 선택한 언론사 크롤링

코드 생략) 아래 블로그를 참고하여 작성하였고 에러는 수정하였다.

참고) https://everyday-tech.tistory.com/12

 

Out[2] : 

 

 

 

 

 

'Python > 크롤링' 카테고리의 다른 글

네이버 뉴스 제목 크롤링  (0) 2023.06.10

+ Recent posts