首页 > 解决方案 > 从播放列表中抓取视频标题

问题描述

我想写一个从 YouTube 音乐播放列表中收集视频标题的刮板,因为有时视频会被删除。我是 python 新手。我通过一篇文章写了代码:

我检查了许多网站上代码的功能(通过更改链接、标签和类)并且一切正常,但不知何故它不适用于 YouTube。

如何从播放列表中获取视频标题?

import requests
from bs4 import BeautifulSoup

url = 'https://www.youtube.com/playlist?list=PLuDh46ey2oy-qmIqPH0o1ZUZ9BFuqvtBn'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
quotes = soup.find_all('a', class_='yt-simple-endpoint style-scope ytd-playlist-video-renderer')

for quote in quotes:
    print(quote.text)

标签: pythonweb-scraping

解决方案


可能您已经从堆栈溢出中阅读过,因为您提到了 YouTube 使用 JavaScript 的相同主题,因此您可以试用selenium它提供自动化浏览器功能的包,您可以从中提取数据以获取更多您可以从文档中阅读的信息

这是代码:

from selenium import webdriver

path="you're path of driver"
driver=webdriver.Chrome(path)

url = 'https://www.youtube.com/playlist?list=PLuDh46ey2oy-qmIqPH0o1ZUZ9BFuqvtBn'
response = driver.get(url)    

main_a=driver.find_elements_by_id("video-title")
lst=[]

for a in main_a:
    lst.append(a.get_attribute("aria-label"))
print(lst)

推荐阅读