【问题标题】:how can i access a youtube 1st search result?如何访问 youtube 第一搜索结果?
【发布时间】:2020-10-26 19:21:21
【问题描述】:

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

它实际上是在说 video_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)

但这会报错

【问题讨论】:

  • 如果video_link 未定义,这意味着if '/watch?v=' in link.get('href') 不适用于您找到的任何链接。
  • 我怀疑页面使用动态javascript来构建视频链接列表,而urllib/beautifulsoup不做javascript。
  • 是他们在数组中获取 ,/watch?v= url 的任何替代方法

标签: python html beautifulsoup download youtube


【解决方案1】:

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

例如:

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2019-12-15
    • 1970-01-01
    相关资源
    最近更新 更多