我想在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()
但是问题是,它会在完成搜索之前在首页上播放第一个视频。
你们可以建议如何播放视频吗?
答案 0 :(得分:1)
您可以通过将所需的搜索查询附加到search_query参数来完全跳过首页的需求:)
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()
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=" + str(video))
# play the video
wait.until(visible((By.ID, "video-title")))
driver.find_element_by_id("video-title").click()