You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Discord机器人中通过视频名称获取YouTube视频URL?

获取YouTube首个视频URL的解决方案

方案1:使用pytube内置搜索(推荐)

你的现有代码依赖浏览器打开页面,无法直接获取视频链接。pytube提供了原生的搜索功能,可以直接获取结果,无需手动处理网页。

修改后的代码:

from pytube import Search

# 提取用户输入的搜索关键词(假设指令前缀已被拆分)
query = " ".join(message.content.split(" ")[1:])

# 执行搜索并获取首个结果
search = Search(query)
first_video = search.results[0]
video_url = first_video.watch_url

# 发送链接到Discord频道
await message.channel.send(f"首个视频链接:{video_url}")

注意事项

  • 确保安装最新版pytube:pip install --upgrade pytube
  • 添加错误处理(比如搜索结果为空时的提示),避免索引越界报错。

方案2:网页抓取(不推荐)

虽然可以通过requests和BeautifulSoup抓取搜索结果,但YouTube的HTML结构频繁变动,且该方式可能违反其服务条款。若仍需尝试:

import requests
from bs4 import BeautifulSoup

# 构造搜索URL(关键词用+连接)
query = "+".join(message.content.split(" ")[1:])
search_url = f"https://www.youtube.com/results?search_query={query}"

# 模拟浏览器请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}

response = requests.get(search_url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")

# 查找首个视频链接(类名可能随时变化)
first_video_url = None
for a_tag in soup.find_all("a", href=True):
    if a_tag["href"].startswith("/watch?v="):
        first_video_url = f"https://www.youtube.com{a_tag['href']}"
        break

if first_video_url:
    await message.channel.send(f"首个视频链接:{first_video_url}")
else:
    await message.channel.send("未找到匹配视频")

原有代码的问题

  • webbrowser.open_new()仅打开浏览器,返回None,因此str(link)是无效值,无法用于YouTube类初始化。
  • 必须通过程序化方式获取搜索结果,而非依赖浏览器交互。

内容的提问来源于stack exchange,提问作者Everyday Student

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 14:23:14