使用 Python 在 youtube 中搜索打开第一个视频

Ara*_*yan 5 python youtube beautifulsoup python-3.x

我尝试了这个,但不知道如何打开第一个视频。此代码在浏览器中打开搜索。

import webbrowser

def findYT(search):
    words = search.split()

    link = "http://www.youtube.com/results?search_query="

    for i in words:
        link += i + "+"

    time.sleep(1)
    webbrowser.open_new(link[:-1])
Run Code Online (Sandbox Code Playgroud)

这样就成功搜索到视频了,但是如何打开第一个结果呢?

Hur*_*ful 4

最常见的方法是使用两个非常流行的库:requestsBeautifulSouprequests获取页面并BeautifulSoup解析它。

import requests
from bs4 import BeautifulSoup

import webbrowser

def findYT(search):
    words = search.split()

    search_link = "http://www.youtube.com/results?search_query=" + '+'.join(words)
    search_result = requests.get(search_link).text
    soup = BeautifulSoup(search_result, 'html.parser')
    videos = soup.select(".yt-uix-tile-link")
    if not videos:
        raise KeyError("No video found")
    link = "https://www.youtube.com" + videos[0]["href"]

    webbrowser.open_new(link)
Run Code Online (Sandbox Code Playgroud)

请注意,建议在 python 中命名变量时不要使用大写字母。