Homebrew Python --Youtube Search Program

A simple search using only requests and Beautiful soup4.

How to use

Y = Youtube([query], result=[num])

query is a search word. Japanese support. num is the number of search results. Up to 20 at the moment due to pagination. Please play around here by yourself.

Y.url    >>Search result url list
Y.title  >>Title list
Y.id     >>ID list (ID? Unique number like JaDJbrwi0gk)
Y.embed  >>URL list for pasting
Y.time   >>Playback time list (may not be in demand)

Example)
print(Youtube("Un-Jash",result=5).url)

>> ['https://www.youtube.com/watch?v=JaDJbrwi0gk', 'https://www.youtube.com/watch?v=yGPAyqxrado', 'https://www.youtube.com/watch?v=tGl2Dp1v0gw', 'https://www.youtube.com/watch?v=myp35PyYk1A', 'https://www.youtube.com/watch?v=Tt1rkp3h1pM', 'https://www.youtube.com/watch?v=XIJqsqOCorw']
Y.select() >>Select one from the search results and return a dictionary for the above information.
key = "url","title","id","embed","time"

Example)
movie = Y.select()
print(movie["url"]) >> https://www.youtube.com/watch?v=JaDJbrwi0gk

It may be efficient to combine it with other download APIs.

script

import requests
from bs4 import BeautifulSoup

class Youtube():
    def __init__(self,query,result=10): #up to max20
        search_url = "https://www.youtube.com/results?search_query=" + query
        req = requests.get(search_url)
        soup = BeautifulSoup(req.text.encode(req.encoding).decode('utf-8','strict'),"html5lib")
        h3s = soup.find_all("h3", {"class":"yt-lockup-title"})[0:result+1]

        self.data = [h3 for h3 in h3s]
        self.url = ["https://www.youtube.com" + h3.a.get('href') for h3 in h3s]
        self.title = [h3.a.get("title") for h3 in h3s]
        self.id = [h3.a.get("href").split("=")[-1] for h3 in h3s]
        self.embed = ["https://www.youtube.com/embed/" + h3.a.get("href").split("=")[-1] for h3 in h3s]
        self.time = [h3.span.text.replace(" -length: ","").replace("。","") for h3 in h3s]
        self.info = [h3.text for h3 in h3s] # >>title-Length: 00:00。

    def select(self):
        values = {"url":self.url,"title":self.title,"id":self.id,"embed":self.embed,"time":self.time}
        info = self.info
        for i in range(len(info)):
            print("%s:%s" % (i,info[i]))
        while True:
            try:
                num = int(input("number:"))
                break
            except:
                print("Please enter the number correctly.")
        results = {
            "url":values["url"][num],
            "title":values["title"][num],
            "id":values["id"][num],
            "embed":values["embed"][num],
            "time":values["time"][num],
            }
        return results

if __name__ == '__main__':
    Y = Youtube(input("Search word:"),result=5)
    movie = Y.select()
    print(movie["url"])

Recommended Posts

Homebrew Python --Youtube Search Program
Homebrew Python Part 3-Amazon Product Search Program
[Python] Shopping program
Search and play YouTube videos in Python
Homebrew search from python module name (ShellScript)
Automatically search and download YouTube videos with Python
Sequential search with Python
Python Exercise 1-Breadth-first search
[Python] Search (itertools) ABC167C
Binary search in Python
homebrew python environment construction
Play youtube in python
[Python] Search (NumPy) ABC165C
Binary search (python2.7) memo
[Python] Binary search ABC155D
python bit full search
Linear search in Python
Binary search with python
Binary search with Python3
Search Twitter using Python
Binary search in Python (binary search)
Get YouTube Comments in Python
[Python] BFS (breadth-first search) ABC168D
Newcomer training program by Python
Get Youtube data with python
YouTube video management with Python 3
Search for strings in Python
Breadth-first search / bidirectional search (Python version)
Search algorithm using word2vec [python]
[Python] DFS (Depth-first Search) ATC001A
Binary search in Python / C ++
Algorithm in Python (binary search)
Full bit search with Python
[Python] DFS (Depth-first Search) ABC157D
Install pyenv from Homebrew, install Python from pyenv
Search engine work with python
Search twitter tweets with python
[Python] Depth-first search and breadth-first search
[Python] BFS (breadth-first search) ABC007C
Streamline web search with python
[Python algorithm] A program that outputs Sudoku answers from a depth-first search
Algorithm in Python (breadth-first search, bfs)
Write a binary search in Python
Setup modern Python environment with Homebrew
HomeBrew can't install Python (at Mavericks)
Learn search with Python # 2bit search, permutation search
Debug python multiprocess program with VSCode
Breadth-first search (BPF) Maybe understood (python)
Prime number generation program by Python
Relink virtualenv python after upgrading Homebrew python
Compatibility diagnosis program written in python
Algorithm in Python (depth-first search, dfs)
Change the Python version of Homebrew
Master linear search! ~ Python implementation version ~
Write a depth-first search in Python
Memorize the Python commentary on YouTube.
Manage each Python version with Homebrew
Reproduce One-Touch Search on Python 3.7.3. (Windows 10)
Depth-first search using stack in Python
When writing a program in Python
Python 2-minute search and its derivation