본문 바로가기

지정한 유튜브 채널의 영상 URL, 조회수, 설명 등을 크롤링 하는 파이선 코드 입니다.


import time
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

options = webdriver.ChromeOptions()

youtube_url = "https://www.youtube.com"

# 창 숨기기
options.add_argument("headless")

# 프록시 사용
PROXY_ADDRESS = "111.111.111.111:9999" # IP:Port #변경 필요

webdriver.DesiredCapabilities.CHROME['proxy'] = {
    "httpProxy": PROXY_ADDRESS,
    "ftpProxy": PROXY_ADDRESS,
    "sslProxy": PROXY_ADDRESS,
    "proxyType": "MANUAL"
}

# 크롤링한 내용을 저장할 엑셀 파일 설정
writer = pd.ExcelWriter('airpage.xlsx', engine='openpyxl')

# 드라이버 설정 (드라이버가 있는 경로를 정확하게 지정 필요)
browser = webdriver.Chrome("./chromedriver.exe", options=options) 

delay = 1
browser.implicitly_wait(delay)

target_url  = youtube_url + "/c/dlwlrma/featured" # iu

browser.get(target_url)

# 화면 크기 최대화
browser.maximize_window()
browser.implicitly_wait(delay)

# 동영상 탭 클릭
browser.implicitly_wait(delay)
browser.find_element_by_xpath('//*[@id="tabsContent"]/tp-yt-paper-tab[2]').click()

body = browser.find_element_by_tag_name('body')

# 스크롤을 한참 내려서 (가능하면 큰 수) body 내용 확보하기
scroll_count = 250
while scroll_count:
    body.send_keys(Keys.PAGE_DOWN)
    browser.implicitly_wait(delay)
    scroll_count -= 1

html0 = browser.page_source
html = BeautifulSoup(html0,'html.parser')

# 영상 목록 획득
video_datas = html.find_all('ytd-grid-video-renderer',{'class':'style-scope ytd-grid-renderer'})

video_url_list = []
for i in range(len(video_datas)):
    url = youtube_url + video_datas[i].find('a',{'id':'thumbnail'})['href']
    video_url_list.append(url)

dataframe = pd.DataFrame({ 'name':[], 'view_count':[], 'youtube_url':[], 'date':[], 'desc' : [] })


for i in range(3):    
#for i in range(len(video_datas)):    
    name = video_datas[i].find('a',{'id':'video-title'}).text    
    url = youtube_url + video_datas[i].find('a',{'id':'thumbnail'})['href']
    for_view_count =video_datas[i].find('div',{'id':'metadata-line'})
    view_count = for_view_count.find_all('span',{'class':'style-scope ytd-grid-video-renderer'})[0].text.split()[1]
    
    cur_url = video_url_list[i]
    browser.get(cur_url) 
    time.sleep(5)
        
    body = browser.find_element_by_tag_name('body')
    
    body.send_keys(Keys.PAGE_DOWN)
    time.sleep(5)
                        
    html0 = browser.page_source
    html = BeautifulSoup(html0,'html.parser')

    moreBtn = browser.find_element_by_xpath('//*[@class="more-button style-scope ytd-video-secondary-info-renderer"]')
    try:
        if moreBtn is not None:
            moreBtn.click()
    except:
        pass
    
    r_date = html.find('div',{'id':'info-strings'}).find('yt-formatted-string').text    
    desc = html.find_all('yt-formatted-string',{'class' : 'content style-scope ytd-video-secondary-info-renderer'})[0].text
    insert_data = pd.DataFrame({ 'name':[name], 'view_count':[view_count], 'youtube_url':[url], 'date':[r_date], 'desc' : [desc] })  
    dataframe = dataframe.append(insert_data)
    dataframe.to_excel(writer, index=False)  
    writer.save()
    print("Crawled : " + str(i))
    
writer.save()


참고 되시길,

건투를 빕니다!





번호 제목 날짜 조회 수
HOT [TIP] PYTHON 에서 "UnicodeDecodeError: 'cp949' codec can't decode byte 0xe2 in position 6987: illegal multibyte sequence" 오류 날때... [52] 2016.02.20 265590
HOT [펌] ARM GCC Inline Assembler Cookbook 2006.08.18 57335
HOT [TIP] R에서 페이스북 페이지 정보 크롤링 하기 [6] 2017.02.11 39306
170 [TIP] 자작 운영체제 AiRPOS 소스를 공개합니다. update 2026.07.04 12777
169 [TIP] MacOS의 크롬에서 keyup 이벤트가 두 번 호출 되는 오류 2023.07.15 1431
168 [TIP] C#의 Hashtable을 안전하게 사용하려면 2023.06.10 1205
167 [TIP] 윈도우 부팅 완료 후 Process.Start로 cmd.exe 실행 결과를 못 얻을 때 2023.05.29 1503
» [TIP] PYTHON으로 유튜브 채널 영상, 조회수, 설명 크롤링 2021.07.22 5988
165 [TIP] vector<Point2f> 파라메터를 JNI에서 자바로 전달하기 (the way how to pass vector<Point2f> variable to JAVA code layer) 2020.06.27 1401
164 [TIP] 외부 (PHP)코드에서 XE에 게시물 등록하기 2020.05.30 4223
163 [TIP] Node.js 에서 현재 기상정보 API 호출하기 2020.02.22 5331
162 [TIP] gcc 빌드중에 /usr/bin/ld: errno: TLS definition in /lib64/libc.so.6 section .tbss mismatches non-TLS reference in ... 와 같은 오류를 만났을 때 2019.11.25 2207
161 [TIP] Windows UWP에서 시리얼 포트가 열리지 않을때 2019.11.08 2395
160 [TIP] 화면 스크롤시 HTML Element가 화면의 중간에 위치하면 감지하기 2019.10.03 5140
159 [TIP] Visual Studio 2019 에서 (배포용)설치파일 만들기 2019.09.30 4682
158 [TIP] Android에서 MS의 Face Rest API사용하기 (How to use the MS Face API on Android) 2019.07.16 1636
157 [TIP] Xcode에서 boost 사용하는 방법 2019.06.28 1158
156 [TIP] 아두이노에서 두근두근 Open API 호출하기 2019.06.04 3943
155 [TIP] AWS Lambda, API Gateway 를 이용하여 S3에 파일 업로드 하기 2018.06.12 3247
154 [TIP] 파이선에서 AWS Lambda API 호출시 Cognito 사용자 토큰으로 권한 확인하기 2018.06.11 2435
153 [TIP] 파이선에서 AWS Cognito 에 Sign-up, Sign-in 하는 예제 2018.06.08 2755
152 [TIP] Ajax에서 AWS Lambda Rest API CALL 하기 (How to call AWS Lambda API from Ajax) 2018.02.12 2248
151 [TIP] 각종 OAuth 로그인 예제 [6] 2018.01.30 2352