如何在YouTube上搜索视频并与Python获取链接

发布于 2025-01-23 13:27:38 字数 943 浏览 2 评论 0原文

我正在尝试根据YouTube中的歌曲标题和艺术家的名字搜索歌曲,并试图获取出现在搜索队列中的第一视频的链接并下载视频,但我面临此错误。您能帮我解决此错误吗?

这就是我试图实现的方式.....

   import re
   import urllib.request
   import urllib.parse
   i=0
   for a in artists:
      for t in titles: 
         input = urllib.parse.urlencode({'search_query': titles[i] + ' by ' + artists[i]})
         #html = requests.get("https://www.youtube.com/results?search_query=" + s_k)
         html = urllib.request.urlopen("http://www.youtube.com/results?" + input)
    
         video_ids = re.findall(r'href=\"\/watch\?v=(.{11})', html.read().decode())
    
         print("https://www.youtube.com/watch?v=" + video_ids[0])
         i+=1
  
       if i == 809:
            break

[这里,“标题”是歌曲标题的列表,“艺术家”是艺术家的列表。 809是两个列表的长度],

但是我得到了 “

i'm trying to search songs based on song titles and artists names from youtube and trying to get the link of the 1st video that appeared in the search queue and download the video, but i'm facing this error. Can u help me to fix this error ?

This is how I tried to implement.....

   import re
   import urllib.request
   import urllib.parse
   i=0
   for a in artists:
      for t in titles: 
         input = urllib.parse.urlencode({'search_query': titles[i] + ' by ' + artists[i]})
         #html = requests.get("https://www.youtube.com/results?search_query=" + s_k)
         html = urllib.request.urlopen("http://www.youtube.com/results?" + input)
    
         video_ids = re.findall(r'href=\"\/watch\?v=(.{11})', html.read().decode())
    
         print("https://www.youtube.com/watch?v=" + video_ids[0])
         i+=1
  
       if i == 809:
            break

[here, 'titles' is a list of song titles and 'artists' is a list of artists. and 809 is the length of both lists]

But I'm getting this error

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱人如己 2025-01-30 13:27:38

此错误意味着Video_IDS列表是空的,因为其第一个索引(即0)超出了范围。您可以将其包装在试试中,除了块:

try:
    print("https://www.youtube.com/watch?v=" + video_ids[0])
except IndexError:
    pass

This error means that the video_ids list is empty since its first index, namely 0, is out of range. You could wrap it in a try except block:

try:
    print("https://www.youtube.com/watch?v=" + video_ids[0])
except IndexError:
    pass
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文