如何使用python selenium查找Youtube视频持续时间?

如何使用python selenium查找Youtube视频持续时间?,python,selenium-chromedriver,Python,Selenium Chromedriver,我正在尝试使用Selenium和Python3来获取视频的持续时间。代码在小视频中运行正常(我已经尝试了30分钟)。但如果视频较长,则不会显示任何内容。我找不到任何解决办法 我的代码: from selenium import webdriver import time, os firefox = webdriver.Chrome() #youtube_url = "https://www.youtube.com/watch?v=oEx-SBpZP_M" # Short Video you

我正在尝试使用Selenium和Python3来获取视频的持续时间。代码在小视频中运行正常(我已经尝试了30分钟)。但如果视频较长,则不会显示任何内容。我找不到任何解决办法

我的代码:

from selenium import webdriver
import time, os

firefox = webdriver.Chrome()

#youtube_url = "https://www.youtube.com/watch?v=oEx-SBpZP_M"  # Short Video
youtube_url = "https://www.youtube.com/watch?v=EMWM2uN8WCQ" # Long Video

firefox.get(youtube_url)

number_of_views = firefox.find_element_by_css_selector('#count > yt-view-count-renderer > span.view-count.style-scope.yt-view-count-renderer')
print(number_of_views.text)

duration = firefox.find_element_by_css_selector('#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > div > span.ytp-time-duration')
print(duration)
print(duration.text)
只要用这个:

duration = firefox.find_element_by_class_name('ytp-cued-thumbnail-overlay-duration')
print(duration)
print(duration.text)

所有这些解决方案的问题在于元素是否可见

只有当我的鼠标悬停在视频上并且元素正在显示时,它才会打印当前时间。否则,如果视频播放时间未显示,selenium将无法抓取元素。这是一张GIF图片,显示了这种情况

您需要在页面上执行javascript以获取当前时间和持续时间。Youtube播放器API具有这两种功能

video_dur = self.driver.execute_script(
                    "return document.getElementById('movie_player').getCurrentTime()")

video_len = self.driver.execute_script(
                    "return document.getElementById('movie_player').getDuration()")

video_len = int(video_len) / 60

print(f"{video_dur}/{video_len})

这将继续工作,即使我不在页面上


它不打印任何内容。只需换行即可打印。正在打印WebElement对象。但在此之后,只有换行符。您是否尝试过添加一些等待时间来定位元素?你的代码会检查youtube上的广告吗?因为这可能会中断元素的定位。
cur_time = driver.find_element_by_class_name("ytp-time-current").text
print(cur_time)
video_dur = self.driver.execute_script(
                    "return document.getElementById('movie_player').getCurrentTime()")

video_len = self.driver.execute_script(
                    "return document.getElementById('movie_player').getDuration()")

video_len = int(video_len) / 60

print(f"{video_dur}/{video_len})