플그래밍/파이써언

[파이썬] 008. 유튜브 영상 제목 검색기

훗티v 2020. 12. 15. 20:44

특정 키워드 검색시 첫 페이지에 나오는 비디오 제목 검색기

 

 

결과

 

 

코드

from bs4 import BeautifulSoup
import requests
import re
import os


if __name__ == '__main__':
    try:
        x = input("검색: ")

        URL = 'https://www.youtube.com/results?search_query=' + x + '&sp=EgIIAw%253D%253D'

        headers = {
            "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36 OPR/67.0.3575.115'}

        page = requests.get(URL, headers=headers)
        soup = BeautifulSoup(page.content, 'html.parser', from_encoding="utf8")
        search_results = soup.findAll("script")

        # script section of the soup
        y = str(search_results)

        # first iteration of the title
        pos = y.find("""title":{"runs":[{"text":""")
        pos_x = pos + 25
        k = y[pos_x:pos+200]
        pos_r = y[pos_x:pos+200]
        sub = """}]"""
        pos_end = pos_x + k.find(sub) - 1
        print(y[pos_x:pos_end])

        # repetition
        i = 1
        f = 19

        while i <= f:
            pos = y.find("""title":{"runs":[{"text":""", pos_x)
            pos_x = pos + 25
            k = y[pos_x:pos+200]
            pos_r = y[pos_x:pos+200]
            sub = """}]"""
            pos_end = pos_x + k.find(sub) - 1
            print(y[pos_x:pos_end])

            i += 1

    except BaseException:
        import sys
        print(sys.exc_info()[0])
        import traceback
        print(traceback.format_exc())
    finally:
        print("\n" + "Press 'Enter' to close the window :)")
        input()

 

 

 

 

 

728x90