Create Opportunities

업무 자동화를 위한 Selenium 크롤링 (1) 본문

나의 생각들

업무 자동화를 위한 Selenium 크롤링 (1)

kimjaeyoon 2023. 7. 15. 21:53

근무하는 인공지능연구센터에서 데이터 구축 업무를 담당하면서 1000시간 가량의 선별된 유튜브 영상을 수집하고, 발화 단위로 영상을 분할하는 작업을 진행했다. 선임 연구원님께서 3일만에 개발한 Data Collector 툴을 사용하여 수집이 간편했지만, 데이터 구축은 사람의 손이 닿을 수 밖에 없는 영역이기에 매우 오랜 시간을 투자해야 했다. 많은 기업과 기관에서 효율적인 데이터 수집과 어노테이션 툴 개발에 힘을 쓰는 이유를 느낄 수 있었다.

초기 input 데이터로 들어갈 영상을 수집하기 위해서는 수동적으로 유튜브 영상을 모으기도 해야 했지만, 크롬 드라이버와 Selenium을 활용해서 영상 링크를 모은 뒤, Data Collector에 입력하는 과정까지 자동화해서 데이터 구축을 빠르게 진행할 수 있었다.

특정 채널이 가지고 있는 모든 동영상의 링크를 가져오고 싶다.

크롬 드라이버를 다운받고, 필요한 라이브러리를 호출한다.

from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service

import time
from selenium.webdriver.common.keys import Keys

ChromeDriverManager().install() 을 통해 크롬 드라이버가 업데이트 되더라도 최신의 드라이버를 사용할 수 있다.

driver를 설정하고, 채널의 url을 driver에게 넘겨준다. 동영상을 많이 가지고 있는 채널이 타겟이기 때문에 PAGE_DOWN을 통해 스크롤을 내리고 싶은 만큼 내려준다.

이제 크롤링을 해주어야 한다. video-title-link를 가져오고 싶기 때문에 CSS_SELECTOR를 사용해서 이를 가져올 수 있다.

titles에 모두 담았다.

 

chrome_options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install(), options=chrome_options))

url = 'https://www.youtube.com/@OOO/videos'

driver.get(url)

for i in range(0, 30):
    driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.PAGE_DOWN)
    time.sleep(1)

titles = driver.find_elements(By.CSS_SELECTOR, '#video-title-link')
print(titles)

Key값으로 영상의 링크가 들어가기 때문에 원하는 포멧에 맞게 링크를 변환하는 함수다.

def convert_youtube_link(link):
    video_id = link.split("watch?v=")[1]
    converted_link = "https://youtu.be/" + video_id
    return converted_link

이제 추출하면 된다. excel의 Workbook 객체를 하나 만들었고, 영상의 제목과 링크를 pair하게 담은 엑셀 파일이 완성되었다.

from openpyxl import Workbook
import re

wb = Workbook()
ws = wb.active
ws.title = 'temp'    # 엑셀 시트 이름이다.
ws.append(['제목', '주소'])

for title in titles:
    href = title.get_attribute('href')
    converted_links = convert_youtube_link(href)
    print(title.text, converted_links)
    ws.append([title.text, converted_links])

wb.save('Youtube_links.xlsx')

Output

'나의 생각들' 카테고리의 다른 글

업무 자동화를 위한 Selenium 크롤링 (2)  (0) 2023.07.15