无法找到 Youtube 观看次数

问题描述 投票:0回答:1

遵循有关抓取 YouTube 观看次数和视频日期的 YouTube 教程 [https://www.youtube.com/watch?v=Cc3mMH8XWC4]

我按照之前的教程制作了每个视频的数据框,其中包含超过 1000 个视频的视图、clean_views、video_url、video_age 和标题。

https://www.youtube.com/watch?v=2s6Oxh3JkG0)我正在尝试解析的视频。如果我可以成功获取视图和 video_date,我计划循环遍历所有数据帧,以更新视图和 video_date。

与我正在观看的教程相比,Youtube 更新了他们的观看次数,使其难以解析。

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

from webdriver_manager.chrome import ChromeDriverManager

-Selenium 到网络抓取。 -用于 webdriver 的 chromeservice 和 ChromeDriverManager。 -导入密钥,以便机器按“结束”按钮一直向下移动页面,加载更多视频。 -导入者,所以我不会收到“未找到名称”错误。

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
for url in youtube_df['video_url']:
    driver.get(url)
    break

告诉驱动程序检查我的数据框中的所有网址。它只关注第一个(就是这个视频(https://www.youtube.com/watch?v=2s6Oxh3JkG0)),因为我写了break。

html = driver.page_source
将驱动程序知道的有关页面的所有内容保存到名为 html 的变量中

soup = BeautifulSoup(html,'html.parser')
使用 beautiful soup 来解析 'html' 变量

soup.find_all('div',{'id':'view-count','class':'style-scope ytd-watch-info-text'}) 
这就是我认为观看次数的地方。在 Arial 标签中它告诉了我这个观点。我认为那里有代码可以使 Arial 隐藏。

如何获取视频的观看次数以及视频的确切日期?

尝试在 Youtube 上查找,所有教程都太旧了。

web-scraping beautifulsoup youtube selenium-chromedriver html-parsing
1个回答
0
投票

您遇到的错误表明

('div',{'id':'view-count','class':'style-scope ytd-watch-info-text'}
调用返回 None,这意味着它没有找到任何与给定条件匹配的元素。 这可能是因为类名
'style-scope ytd-watch-info-text'
不是唯一的,这意味着您所需的数据不在您的选择范围内。您不需要应用 for 循环来获取正确的 html 元素选择。您可以尝试通过应用我的代码中的元素选择来获取所需的数据。现在一切正常了。

脚本:

import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup


options = webdriver.ChromeOptions()
options.add_argument("start-maximized")

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),options=options)
video_url=["https://www.youtube.com/watch?v=2s6Oxh3JkG0"]
for url in video_url:
    driver.get(url)
    time.sleep(5)

soup = BeautifulSoup(driver.page_source, 'lxml')
view_count = soup.select_one('span.bold.style-scope.yt-formatted-string:first-child').get_text()
actual_view_count = soup.select_one('.view-count').get_text()
date = soup.select_one('span.bold.style-scope.yt-formatted-string:nth-child(3)').get_text()
meta_tags = soup.find_all('meta')
upload_date = ""
for tag in meta_tags:
    if tag.get('itemprop') == 'uploadDate':
        upload_date = tag.get('content')
        break

print('View count:' , view_count)
print('Actuai View count:', actual_view_count)
print('Date:', date)
print('Upload date:', upload_date)

输出:

View count: 12K views
Actuai View count: 12,855 views
Date: 1 day ago
Upload date: 2024-02-17T09:00:02-08:00
© www.soinside.com 2019 - 2024. All rights reserved.