I want to search and play a video using Selenium in Python.
Here is the code:
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()
But the problem is, it plays the first video on the home page before it completes searching.
Can you guys suggest how to play the video?
We can perform Google search automation with Selenium webdriver in Python. First of all, we shall locate the Google search box with the help of any of the locators like id, css, xpath, class, or name. Then simulate the action of pressing the ENTER key with the help of Keys. ENTER/Keys.
Video streaming is becoming more popular these days, but you may not want to automate it through UI. More often than not, Selenium won't be able to recognize video controls. JavaScript Executor and flex-ui-selenium will work to some extent, but they are not entirely reliable.
We can search for a keyword in Google using Selenium webdriver in Java. In order, to perform a search, we have to first land on the Google page with the help of the get method. Then identify the search edit box with the help of any of the locators like id, name, class, xpath, tagname, or css.
You could bypass the need of starting off at the homepage completely by appending the desired search query to the search_query parameter :)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With