【问题标题】:Open first video by searching in youtube, using Python通过在 youtube 中搜索,使用 Python 打开第一个视频
【发布时间】:2020-07-23 01:34:35
【问题描述】:

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

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])

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

【问题讨论】:

  • 这能回答你的问题吗? Call to operating system to open url?
  • 不,谢谢,我想,我必须通过解析在 HTML 文档中找到第一个视频的链接.. 但我想要简单的方法)
  • 你不能用那个代码搜索(我猜)?
  • 这只是打开搜索而已
  • 您必须为此进行解析。想要一个代码吗?

标签: python python-3.x beautifulsoup youtube


【解决方案1】:

最常见的方法是使用两个非常流行的库: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)

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

【讨论】:

  • 是的,这回答了您的问题。选择这个作为你的答案,这样问题就结束了
【解决方案2】:

为此,您必须进行网络抓取。 Python 看不到屏幕上的内容。您必须抓取您正在搜索的 youtube 页面,然后您可以打开例如出现的第一个 <a>。 (''是html中的url标签)

你需要的东西:

  • 例如BeautifulSoup 或硒
  • 请求

这应该是你做你想做的所有事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2012-10-11
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    相关资源
    最近更新 更多