forked from geekcomputers/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
youtube.py
30 lines (24 loc) · 927 Bytes
/
youtube.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
'''
Author: Abhinav Anand
git: github.com/ab-anand
mail: [email protected]
Requirements: requests, BeautifulSoup
'''
import os
import webbrowser
import requests
from bs4 import BeautifulSoup
headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'}
query = input('Enter the song to be played: ')
query = query.replace(' ', '+')
# search for the best similar matching video
url = 'https://www.youtube.com/results?search_query=' + query
source_code = requests.get(url, headers=headers, timeout=15)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
# fetches the url of the video
songs = soup.findAll('div', {'class': 'yt-lockup-video'})
song = songs[0].contents[0].contents[0].contents[0]
link = song['href']
webbrowser.open('https://www.youtube.com' + link)