gpt4 book ai didi

python - 如何在 Python 中使用 Selenium 在 YouTube 上搜索和播放视频?

转载 作者:行者123 更新时间:2023-12-01 13:15:30 25 4
gpt4 key购买 nike

我想在 Python 中使用 Selenium 搜索和播放视频。
这是代码:

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.maximize_window()
driver.get(www.youtube.com)

wait = WebDriverWait(driver, 3)
presence = EC.presence_of_element_located
visible = EC.visibility_of_element_located

# Search for the video.
time.sleep(1)
wait.until(visible((By.NAME, "search_query")))
driver.find_element_by_name("search_query").click()
driver.find_element_by_name("search_query").send_keys(video)
driver.find_element_by_id("search-icon-legacy").click()

# Play the video.
wait.until(visible((By.ID, "video-title")))
driver.find_element_by_id("video-title").click()
但问题是,它在完成搜索之前播放主页上的第一个视频。
你们能建议如何播放视频吗?

最佳答案

您可以通过将所需的搜索查询附加到 search_query 参数来完全绕过从主页开始的需要:)

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.maximize_window()

wait = WebDriverWait(driver, 3)
presence = EC.presence_of_element_located
visible = EC.visibility_of_element_located

# Navigate to url with video being appended to search_query
driver.get('https://www.youtube.com/results?search_query={}'.format(str(video))

# play the video
wait.until(visible((By.ID, "video-title")))
driver.find_element_by_id("video-title").click()

关于python - 如何在 Python 中使用 Selenium 在 YouTube 上搜索和播放视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55560173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com