[crawler] youtube(selenium)

2021. 5. 17. 09:25Python/코딩

Ver. Jupyter Notebook (Anaconda3)

▶ crawler_yotube(selenium)

수집: 제목, 조회수, 날짜, 좋아요, 싫어요, 댓글

코딩: github

 

JeongJaeyoung0/crawler

Contribute to JeongJaeyoung0/crawler development by creating an account on GitHub.

github.com

210517

# crawler_Youtube
step 1. url 수집: 검색어 입력, 크롤링 글 개수 입력
step 2. 크롤링: 제목, 조회수, 날짜, 좋아요, 싫어요, 댓글

pwd

### step 0. 준비
import sys    # 시스템
import os     # 시스템

import pandas as pd    # 판다스 : 데이터분석 라이브러리
import numpy as np     # 넘파이 : 숫자, 행렬 데이터 라이브러리

from selenium import webdriver    # 웹 브라우저 자동화
import time                       # 시간 지연
import math                       # 올림, 내림
from selenium.webdriver.common.keys import Keys
from tqdm import tqdm   # 진행상황 표시

### step 1. url 수집
keyword = input('검색어 입력: ')
articles_number = int(input('크롤링 글 개수: '))

# 크롬 웹브라우저 실행
driver = webdriver.Chrome(r"G:\내 드라이브\exe\chromedriver.exe")

# 키워드로 접속
driver.get("https://www.youtube.com/results?search_query={}".format(keyword))
time.sleep(2)

# 스크롤 다운 함수
def scroll_down(driver):
    driver.execute_script("window.scrollTo(0, 99999)")
    time.sleep(2)
    
# 영상 목록 스크롤 다운 실행
for i in range(math.ceil((articles_number-26)/20)):
    scroll_down(driver)
    
crawling_list = []
url_list = []

# url 수집
crawling_list = driver.find_elements_by_tag_name('h3 > a')

for crawling in crawling_list:
    url = crawling.get_attribute('href')   
    url_list.append(url)
driver.close()
url_list = url_list[:articles_number]
print('크롤링할 글 수: ', len(url_list))
url_list[0]

### step 2. 크롤링
%%time
dict = {}
count = 0

for url in tqdm(url_list):
    # url 열기
    driver = webdriver.Chrome(r"G:\내 드라이브\exe\chromedriver.exe")
    driver.get(url)
    time.sleep(2)

    driver.execute_script("window.scrollTo(0, 400)")
    time.sleep(1)
    
    info = driver.find_element_by_css_selector('.style-scope ytd-video-primary-info-renderer').text.split('조회수')

    # 제목
    title = info[0].split('\n')[-2]
    
    # 조회수, 날짜 위치 추출
    for i in info[1].split('\n'):
        if '회' in i:
            view_date = i

    # 조회수
    #view = int(view_date[0].split('•')[0].replace('회', '').replace(',',''))
    view = int(view_date.split('•')[0].replace('회', '').replace(',',''))
    # 날짜
    #date = view_date[0].split('•')[1]
    date = view_date.split('•')[1]
    # 좋아요
    like = info[1].split('\n')[1]
    # 싫어요
    dont_like = info[1].split('\n')[2]

    try:
        # 댓글 수
        review_cnt = driver.find_element_by_xpath('/html/body/ytd-app/div/ytd-page-manager/ytd-watch-flexy/div[5]/div[1]/div/ytd-comments/ytd-item-section-renderer/div[1]/ytd-comments-header-renderer/div[1]/h2/yt-formatted-string/span[2]').text.replace(',', '')
        print('<',count,'>', title, '( 댓글 수:', review_cnt,')')
        
        # 댓글 스크롤 다운
        for i in range(math.ceil((int(review_cnt)-20)/20)):
            scroll_down(driver)
        print('1. 스크롤 다운 완료')
        
        # 광고 끄기
        time.sleep(10)
        try:
            driver.find_element_by_css_selector("#main > div > ytd-button-renderer").click()
            print('2. 광고 창 제거함')
        except:
            print('2. 광고 창 안뜸')
        
        try:
            # 답글 n개 보기 클릭
            buttons = driver.find_elements_by_css_selector("#more-replies > a")
            for button in buttons:
                button.send_keys(Keys.ENTER)
                time.sleep(1)
                button.click()
            time.sleep(1)
            print('3. 답글 보기 클릭 완료')
        except:
            print('3. 답글 보기 없음')
        
        try:
            # 답글 더보기 클릭
            buttons_more = driver.find_elements_by_css_selector('#continuation > yt-next-continuation > tp-yt-paper-button')
            for button in buttons_more:
                button.send_keys(Keys.ENTER)
                time.sleep(1)
            print('4. 답글 더보기 클릭 완료')
        except:
            print('4. 답글 더보기 없음')
        
        # 댓글 수집
        review_list = []
        reviews = driver.find_elements_by_css_selector('#content-text')
        for review in reviews:
            review = review.text
            review_list.append(review)
        print('5. 댓글 수집 :', len(review_list))
            
    except:
        review_cnt = ''
        review_list = ''
        print('댓글 차단')
            
    target_info = {}
    target_info['제목'] = title
    target_info['조회수'] = view
    target_info['날짜'] = date
    target_info['좋아요'] = like
    target_info['싫어요'] = dont_like
    target_info['댓글 수'] = review_cnt
    target_info['댓글'] = review_list

    dict[count] = target_info

    driver.close()
    count += 1
    time.sleep(1)
    
# 판다스화
df = pd.DataFrame.from_dict(dict, 'index')
df

# 엑셀 저장
df.to_excel('crawler_youtube_review_{}.xlsx'.format(keyword))

'Python > 코딩' 카테고리의 다른 글

[crawler] naver cafe_게시판 글 목록  (0) 2021.05.19
[python] crawler_google image  (0) 2021.05.18
[wordcloud] kakao_talk  (0) 2021.05.15
[python] crawler_naver 부동산  (0) 2021.05.14
[python] crawler (AirKorea)  (0) 2021.05.10