问题描述
我想编写一个 Python 脚本,当我开始播放 Youtube 视频时暂停 Spotify 播放,并在视频结束/暂停时恢复播放。为此,我显然必须识别 Firefox 当前是否正在播放视频,但是经过初步研究,我还没有得出有用的结果。有谁知道允许此类功能的库或类似库?
或者,识别从 Firefox 应用程序播放的音频可能就足够了,因为让脚本也影响例如抽搐流或类似。我使用的是 Windows 10。
解决方法
因此,首先您可能需要检查 yt 当前是否在任何选项卡上打开:
def get_youtube_window_handle(driver):
for handle in driver.window_handles:
driver.switch_to.window(handle)
if driver.current_url.startswith('youtube.com'):
return handle
return None
然后检查视频是否暂停。我想使用 JS 和调用 Youtube iframe API 更容易(例如参见 player.getPlayerState()
)。
现在在 Python 中,我不太确定什么是最好的方法。 可能类似的事情会检查视频是否已暂停,但请稍加注意:
import time
def yt_video_is_paused(driver):
start_current_time = driver.find_element_by_class_name("ytp-time-current").text
time.sleep(1)
end_current_time = driver.find_element_by_class_name("ytp-time-current").text
return start_current_time == end_current_time
您可以调用这两个函数,如下所示:
from selenium import webdriver
driver = webdriver.Firefox()
yt_tab = get_youtube_window_handle(driver)
if yt_tab:
driver.switch_to.window(yt_tab)
if yt_video_is_paused(driver):
# do something
您可能还需要考虑在多个标签页上打开 Youtube 时会发生什么情况。