-2

我正在尝试通过 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()

''''
4

2 回答 2

2

为此,它需要执行一些 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})
于 2020-10-16T15:34:42.517 回答
-1

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

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()
于 2020-10-16T15:14:33.940 回答