我怎样才能访问 youtube 1st 搜索结果?

how can i access a youtube 1st search result?

实际上我尝试了一个代码但它不起作用任何人都可以帮助我修复它

实际上是说 video_link 未定义

我认为 link 在 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)

但这是错误的

要获得正确版本的 YouTube HTML 页面,请使用正确的 User-Agent HTTP header。

例如:

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')

打印:

/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.