如何在不使用API的情况下根据用户输入内容获取YouTube视频的点赞数?

0 投票
1 回答
34 浏览
提问于 2025-04-13 14:45

我正在尝试写一个程序,用来获取链接,比如用户选择的内容相关的所有视频链接。

目前,我写的代码只返回空的结果集,什么都没有。请问我哪里出错了?

import requests
from bs4 import BeautifulSoup
import tkinter
from tkinter import simpledialog

root = tkinter.Tk()
root.withdraw()


content = simpledialog.askstring("Input", "Veuillez saisir une chaîne de caractères :", parent=root)

url = f"https://www.youtube.com/results?search_query={content}"

response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

set_likes = set()
set_links = set()

#getting number of views
for video in soup.find_all("a", href=True):
    video_href = video['href']
    #Verify if the url is correct
    if "/watch?" in video_href:
        video_url = f"https://www.youtube.com{video_href}"
        video_response = requests.get(video_url)
        video_soup = BeautifulSoup(video_response.content, 'html.parser')
        
        #Getting number of likes
        try:
            likes = video_soup.find("button", class_="like-button-renderer-like-button").text
            set_likes.add(likes)
            set_links.add(video_url)
        except AttributeError:
            print(f"Impossible to get links for the videos: {video_url}")

# Afficher les résultats
print("links:", set_links)
print("likes:", set_likes)



谢谢你的帮助。

1 个回答

0

使用 requests 这个工具抓取纯 HTML 网站或者像 JSON API 这样的内容是没问题的。但是,YouTube 和其他一些现代应用的工作方式和静态网站不一样——它们会运行一些脚本,在下载完基本的 HTML 文件后再下载和渲染整个网站。这就导致你用纯粹的 requests 抓取时,只能拿到基本的 HTML 代码,里面可能会有一些 JS 的引用,但不会包含任何具体的内容。

想看看效果如何,可以试试:

r = requests.get('https://any_website')
r.text

然后查看结果。在很多情况下,你可能会发现没有什么有用的内容。

为了抓取以这种方式渲染的网站,你需要模拟一个浏览器,这样网站就会像普通用户在 Chrome 或 Firefox 中渲染一样工作。为此,你可以尝试:

  • Selenium
  • Scrapy(这里的文档对理解这个问题非常有帮助。)

撰写回答