【发布时间】:2021-07-23 17:48:39
【问题描述】:
我制作了一个 Python 程序,它使用 Selenium 打开我的 Youtube 播放列表,我想在观看所有视频时关闭该浏览器。
(我尝试使用time.sleep(),但问题是 Youtube 广告)。
那么,有什么方法可以让我在观看完所有视频后自动关闭浏览器?
【问题讨论】:
标签: python selenium webautomation
我制作了一个 Python 程序,它使用 Selenium 打开我的 Youtube 播放列表,我想在观看所有视频时关闭该浏览器。
(我尝试使用time.sleep(),但问题是 Youtube 广告)。
那么,有什么方法可以让我在观看完所有视频后自动关闭浏览器?
【问题讨论】:
标签: python selenium webautomation
视频播放完毕后,//div[@class='ytp-autonav-endscreen-button-container'] 元素出现,因此您可以等到该元素出现,然后关闭驱动程序。
您也可以通过类名'ytp-autonav-endscreen-button-container' 或其中的其他按钮/元素简单地找到它。
所以盯着视频后使用
WebDriverWait(driver, delay).until(EC.visibility_of_element_located((By.ID, 'ytp-autonav-endscreen-button-container')))
delay 是足够让视频完成的时间。
详细了解 webdriver 显式等待条件here
不要忘记添加必要的导入
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
【讨论】:
WebDriverWait 完成,该元素就会显示在页面上。如果超时会抛出异常。
我建议分步进行。
第一步:
等待播放列表中的最后一个视频:
通过文字:
last_video = driver.find_element_by_css_selector("#secondary .index-message.style-scope.ytd-playlist-panel-renderer:nth-child(1)").text == "10 /10"
或者直接等待播放列表中的最后一个元素:
last_video = driver.find_element_by_css_selector("#secondary #items>.style-scope.ytd-playlist-panel-renderer:last-of-type").get_attribute("selected")
第二步:
在第一个条件为真后,等待此视频结束,使用此定位器(重播按钮)
video_ends = driver.find_element_by_css_selector(".ytp-chrome-controls button[title=Replay]")
为此,您需要导入:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
并像这样使用它:
wait = WebDriverWait(driver, timeout_in_seconds)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#secondary .index-message.style-scope.ytd-playlist-panel-renderer:nth-child(1)").text == "10 /10")))
超时取决于播放列表的长度。
这不是一个快速的任务,没有人会同意在这里为你完成它。
【讨论】: