[Python] YouTube 동영상을 자동으로 다운로드

[Python] YouTube 동영상을 자동으로 다운로드

2022-10-18 last update

15 minutes reading tutorial productivity vscode python
YouTube 동영상을 자동으로 다운로드하는 데모 플레이용 장난감 프로젝트입니다. 이것은 확실히 가장 효과적인 방법은 아니지만 Python 초보자에게는 충분히 간단합니다.

요구 사항:
  • 창 7+
  • 파이썬 3.7+
  • VS 코드

  • 설정
    파이튜브 설치:

    pip install pytube
    


    클릭늄 설치:
    Visual Studio Code Extension 마켓플레이스에서 Clicknium을 검색합니다.

    시작 페이지에 따라 구성을 완료하십시오.

    웹 브라우저 시작:
    youtube.py와 같은 VS 코드로 Python 파일 만들기

    from clicknium import clicknium as cc
    def main():
        tab = cc.chrome.open("https://www.youtube.com")
    
    if __name__ == "__main__":
        main()
    


    F5 키를 눌러 코드를 실행합니다. Chrome 브라우저가 열리고 YouTube 홈 페이지로 이동합니다.

    포착:
    예를 들어 Taylor Swift와 같은 Youtuber의 홈 페이지로 이동하여 비디오 링크를 가져옵니다. 코끼리를 냉장고에 넣는 5단계와 같은 것:
  • 검색창에 Taylor Swift를 입력하세요.
  • 검색 버튼을 클릭합니다.
  • Taylor의 홈페이지로 들어가려면 Taylor의 링크를 클릭하십시오.
  • 클릭하면 동영상 페이지로 이동합니다.

  • 네 가지 관련 UI 요소가 있습니다.
  • 검색 상자
  • 검색 버튼
  • 검색 결과의 이름
  • 비디오 탭

  • Clicknium은 로케이터(일명 선택기)를 사용하여 UI 요소를 찾습니다. 로케이터를 생성하는 레코더를 제공합니다. 위의 코드를 사용하여 브라우저를 열고 VS Code로 돌아가서 레코더를 시작할 수 있습니다.

    화면의 요소 위에 마우스를 놓고 Ctrl 키를 누른 상태에서 클릭하면 UI 요소에 대한 로케이터가 자동으로 생성됩니다. 오른쪽 상단 모서리에 있는 검색 상자, 검색 버튼 및 Taylor의 이름을 캡처합니다.


    각 캡처는 UI 요소에 대한 로케이터 대상을 생성합니다. 로케이터의 이름을 의미 있는 이름으로 바꿀 수도 있습니다. 완료 버튼을 클릭하고 캡처 후 VS Code로 돌아갑니다.


    로케이터를 find_element 함수에 전달하여 UI 요소를 가져옵니다. 그런 다음 set_text 함수를 사용하여 검색 상자에 "Taylor Swift"를 입력합니다. 다음 줄은 검색 버튼을 얻기 위해 동일한 방법을 사용하고 클릭 기능을 사용하여 마우스 클릭을 표시합니다. 위의 코드를 실행하면 홈페이지에 들어갈 수 있습니다. 같은 방법으로 비디오 목록으로 들어갑니다.

    from clicknium import clicknium as cc, locator
    from clicknium.common.enums import *
    
    def main():
        tab = cc.chrome.open("https://www.youtube.com")
        tab.find_element(locator.chrome.youtube.searchBar).set_text(
            "Taylor Swift", by='sendkey-after-click')
        tab.find_element(locator.chrome.youtube.button_search_icon_legacy).click()
        tab.find_element(locator.chrome.youtube.TS).click()
    
    if __name__ == "__main__":
        main()
    


    위 이미지의 비디오에 대한 모든 주소를 가져와야 합니다. 주소는 로케이터 속성에서 얻을 수 있지만 너무 많은 로케이터를 생성해야 하는 경우 지루할 것입니다. Clicknium Recorder에서 제공하는 유사한 요소 캡처 기능을 사용할 수 있습니다. 유사한 요소 버튼을 클릭하고 동일한 방법을 사용하여 단일 요소를 캡처합니다. Clicknium은 유사한 요소를 자동 감지하고 유사한 모든 UI 요소를 대상으로 하는 하나의 로케이터를 생성합니다.


        tab = cc.chrome.open("https://www.youtube.com")
        tab.find_element(locator.chrome.youtube.searchBar).set_text(
            "Taylor Swift", by='sendkey-after-click')
        tab.find_element(locator.chrome.youtube.button_search_icon_legacy).click()
        tab.find_element(locator.chrome.youtube.TS).click()
        tab.find_element(locator.chrome.youtube.div_video).click()
        tab.wait_appear(locator.chrome.youtube.a_video_title)# wait untill loading videos finish
        vidioTitles = tab.find_elements(locator.chrome.youtube.a_video_title)
    


    비디오 목록의 비동기 로드 때문에 UI 요소가 나타날 때까지 대기하려면 wait_appear를 사용해야 합니다. 로케이터가 여러 비디오를 대상으로 했기 때문에 find_elements를 사용하여 UI 요소 배열을 가져옵니다. href에서 가져온 동영상에 관련 경로를 추가하여 YouTube 주소에서 동영상 URL을 가져올 수 있습니다.

    비디오 URL로 비디오를 얻으려면 Pytube를 사용하십시오. Pytube는 주어진 해상도에 따라 비디오를 다운로드할 수 있습니다. 나열된 일부 스트림에는 비디오 코덱과 오디오 코덱이 모두 있는 반면 다른 스트림에는 최고 품질 스트림에 대한 비디오 또는 오디오만 있는 것을 알 수 있습니다. 자세한 내용 Working with Streams and StreamQuery

    암호:

    from pytube import YouTube
    from clicknium import clicknium as cc, locator
    from clicknium.common.enums import *
    
    def downloadVideo(url):
        SAVE_PATH = "C:\\Users\\Kay\\Downloads\\Youtube"
        try:
            yt = YouTube(url)
            yt.streams.filter(res="1080p").first().download(output_path=SAVE_PATH)
        except:
            print("Connection Error")  # to handle exception
    
        # filters out all the files with "mp4" extension
        print('Task Completed!')
    
    
    def main():
        urlArrary = []
        tab = cc.chrome.open("https://www.youtube.com")
        tab.find_element(locator.chrome.youtube.searchBar).set_text(
            "Taylor Swift", by='sendkey-after-click')
        tab.find_element(locator.chrome.youtube.button_search_icon_legacy).click()
        tab.find_element(locator.chrome.youtube.TS).click()
        tab.find_element(locator.chrome.youtube.div_video).click()
        tab.wait_appear(locator.chrome.youtube.a_video_title)
        videoTitles = tab.find_elements(locator.chrome.youtube.a_video_title)
        for locat in videoTitles:
            url = "https://www.youtube.com" + locat.get_property("href")
            urlArrary.append(url)
        tab.close()
    
        for v in urlArrary:
            downloadVideo(v)
    
    
    if __name__ == "__main__":
        main()