【问题标题】:How can I get Youtube video length?如何获取 Youtube 视频长度?
【发布时间】:2020-10-16 15:07:02
【问题描述】:

我正在尝试通过 selenium 自动化 youtube 但我被困在两者之间 我想创建一个程序,它会列出用户必须听的歌曲列表,然后它会自动在 youtube 上播放歌曲。所以我可以播放一首歌,但之后我不知道如何自动获取视频的长度,然后等到视频结束,然后搜索下一首歌曲并播放它。(就像一个循环,直到列表结束) 请帮帮我 我的代码

''''
import os
from selenium import webdriver
from getpass import getpass
from time import sleep
from selenium.webdriver.chrome.options import Options

# Adblocker Extension 
executable_path = "/webdrivers"
os.environ["webdriver.chrome.driver"] = executable_path
chrome_options = Options()
chrome_options.add_extension('E:\\ad\\ads4.crx')

# Chrome Driver
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("https://youtube.com.")
sleep(2)

# Song name to search :
searchbox = driver.find_element_by_xpath('/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div/div[1]/input')
searchbox.send_keys('Can e Sanem - Mean It')

searchbutton = driver.find_element_by_xpath('//*[@id="search-icon-legacy"]')
searchbutton.click()

# Play the first song on the list
playbutton = driver.find_element_by_xpath('/html/body/ytd-app/div/ytd-page-manager/ytd-search/div[1]/ytd-two-column-search-results-renderer/div/ytd-section-list-renderer/div[2]/ytd-item-section-renderer/div[3]/ytd-video-renderer[1]/div[1]/div/div[1]/div/h3/a/yt-formatted-string')
playbutton.click()

# Play the nect song after the first ends
# playnext = driver.find_element_by_xpath('/html/body/ytd-app/div/ytd-page-manager/ytd-watch-flexy/div[4]/div[1]/div/div[11]/ytd-watch-next-secondary-results-renderer/div[2]/ytd-compact-autoplay-renderer/div[2]/ytd-compact-video-renderer/div[1]/div')
# playnext.click()

''''

【问题讨论】:

标签: python python-3.x selenium-webdriver web-scraping


【解决方案1】:

要做到这一点,需要执行一些 JS 代码来获取持续时间,而 youtube player api 有一个功能。

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

video_len = int(video_len) / 60

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

【讨论】:

  • @diven 我将省略self driverexecute_script 的解释,因为你有这方面的官方文档。如果您对任何硒方法有任何不了解的地方,请询问。基本上video_len 在 Javascript 中有一个带有你的玩家 ID 的返回值,它调用我告诉你需要的 Js Methof。然后要获得分钟,只需将结果除以 60(秒),最后使用print 显示格式如下的输出 - 例如:“1:20 / 5:00”。 (当前/长度)
【解决方案2】:

试试这条线来获取视频持续时间:

driver.find_element_by_xpath('//span[@class="ytp-time-duration"]').text

如果你想以秒为单位:

import time
import datetime

duration = driver.find_element_by_xpath('//span[@class="ytp-time-duration"]').text
_time = time.strptime(duration, '%M:%S')
seconds = datetime.timedelta(minutes=_time.tm_min,seconds=_time.tm_sec).total_seconds()

【讨论】:

    猜你喜欢
    • 2013-06-18
    • 2015-07-25
    • 2011-12-08
    • 2011-09-07
    • 1970-01-01
    • 2018-06-28
    • 2011-12-08
    • 2016-02-15
    • 2011-09-07
    相关资源
    最近更新 更多