我正在尝试使用 Selenium 和 python 3 获取视频持续时间。代码可以正常处理小视频(我已经尝试了长达 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)
最佳答案
所有这些解决方案的问题在于元素是否可见。
即
cur_time = driver.find_element_by_class_name("ytp-time-current").text
print(cur_time)
如果我的鼠标悬停在视频上并且元素正在显示,它只会打印 cur_time。否则,如果视频播放时间不显示,selenium 将无法抓取该元素。这是显示情况的 GIF。
https://i.imgur.com/bmWdC7A.gif
您需要在页面上执行javascript 来获取当前时间和时长。 Youtube Player 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})
https://i.imgur.com/TEdFZ0z.gif
即使我不在页面上,这也会继续工作。
关于python - 如何使用 python selenium 查找 Youtube 视频持续时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51797145/