Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
CHATBOT/youtubeSearch.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
57 lines (44 sloc)
2.11 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
find artists on youtube using beautifulsoup4 library | |
''' | |
import time | |
import requests #-- found at docs.python-requests.org | |
from bs4 import BeautifulSoup #--found at https://www.crummy.com/software/BeautifulSoup/bs4/doc/ | |
youtube_api_v3_key='AIzaSyALTsGjGJz0LDgYCw5jI7SltfQbUTRUUl0' #used to access youtube api for music duation | |
def get_vid_link(artist): | |
'''this function takesin a string and search youtube for that string. it gets the first link on the page and return an id(video id )''' | |
url="https://www.youtube.com/results?search_query=" + artist | |
response=requests.get(url) #---request.get() is a a funtion from http://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls | |
links=response.text #--coverting response object to text: | |
#---The code below is a modified version that can be found in the BeatifoulSoup Docs at :---------- | |
#https://www.crummy.com/software/BeautifulSoup/bs4/doc/ | |
data=BeautifulSoup(links,'html.parser') | |
list_links=[] | |
for tag in data.find_all('a'):#--retrieving every link from the <a> tag in data | |
hf=tag.get('href') | |
if '/watch?v' in hf: | |
list_links.append(hf) | |
if len(list_links)==1: | |
return(list_links[0]) #--selecting the first link as basedon youtube's relevance filter to input | |
break | |
#----END of code inspired from https://www.crummy.com/software/BeautifulSoup/bs4/doc/ ------------- | |
def extract_id(link): | |
id_sum=link.split('=') | |
id=id_sum[1] | |
return id | |
def lenght_song(vid_id): | |
'''this function takes in the id of a vieo and returns the lenght of the vidoe as an interger''' | |
vid_id=extract_id(vid_id) | |
url="https://www.googleapis.com/youtube/v3/videos?id="+vid_id+"&key="+youtube_api_v3_key+"&part=contentDetails" | |
response=requests.get(url) | |
response=response.json() | |
vid_length=response['items'][0]['contentDetails']['duration'] | |
vid_length_list=[int(num) for num in vid_length if num.isdigit()] | |
total_time=(int(vid_length_list[0])*60)+int((vid_length_list[1])) | |
#print(total_time/100) | |
return total_time | |
if __name__ == '__main__': | |
print(lenght_song('watch?v=2tJipvjt4w4')) | |
t=(lenght_song('watch?v=2tJipvjt4w4')) | |
time.sleep(t/100) | |
print('time done') | |