Answer a question

actually i tried a code but it doesnt work could any one help me to fix it

its actually saying that the video_link is not defined

i think error in for link in soup.find_all('a'):

import os
import glob
from bs4 import BeautifulSoup
import urllib
from urllib.parse import quote_plus as qp

DEFAULT_AUDIO_QUALITY = '320K'

search = ' '
# We do not want to except empty inputs :)
while search == '':
  search = raw_input('Enter your query ')
search = qp(search)

print('Making a Query Request! ')

response = urllib.request.urlopen('https://www.youtube.com/results?search_query='+search)
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
for link in soup.find_all('a'):
    if '/watch?v=' in link.get('href'):
      print(link.get('href'))
      # May change when Youtube Website may get updated in the future.
      video_link = link.get('href')
      break

video_link =  'http://www.youtube.com/'+video_link
command = ('youtube-dl --extract-audio --audio-format mp3 --audio-quality ' +
           DEFAULT_AUDIO_QUALITY + ' ' +video_link)

print ('Downloading...')
os.system(command)

but this is giving error

Answers

To get correct version of YouTube HTML page, use correct User-Agent HTTP header.

For example:

import requests
from bs4 import BeautifulSoup

search = 'tree'

headers = {'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'}

html = requests.get('https://www.youtube.com/results?search_query='+search, headers=headers).text
soup = BeautifulSoup(html, 'html.parser')
for link in soup.find_all('a'):
    if '/watch?v=' in link.get('href'):
      print(link.get('href'))
      # May change when Youtube Website may get updated in the future.
      video_link = link.get('href')

Prints:

/watch?v=ZKAM_Hk4eZ0
/watch?v=ZKAM_Hk4eZ0
/watch?v=wCQfkEkePx8
/watch?v=wCQfkEkePx8
/watch?v=Va0vs1fhhNI
/watch?v=Va0vs1fhhNI
/watch?v=kUDPr5xPYhM
/watch?v=kUDPr5xPYhM
/watch?v=kSjXOebB7eI
/watch?v=kSjXOebB7eI
/watch?v=IiDkVftBgak
/watch?v=IiDkVftBgak
/watch?v=F3hTW9e20d8
/watch?v=F3hTW9e20d8
/watch?v=Iy-dJwHVX84
/watch?v=Iy-dJwHVX84

... etc.
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐