gpt4 book ai didi

python - 我如何访问YouTube第一搜索结果?

转载 作者:行者123 更新时间:2023-12-03 05:34:26 25 4
gpt4 key购买 nike

实际上我尝试了一个代码,但是它不起作用,有人可以帮助我修复它吗
实际上是说未定义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)
但这给了错误

最佳答案

要获取正确版本的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.

关于python - 我如何访问YouTube第一搜索结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62759936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com