DEV Community

Cover image for Selenium for Beginners: Automating a Search on YouTube
Rusydy
Rusydy

Posted on • Edited on

Selenium for Beginners: Automating a Search on YouTube

Selenium is a popular open-source tool that automates web browsers and is commonly used for testing web applications. In this article, we will use the Firefox driver to navigate to the YouTube home page, locate the search bar, and enter a search query.

Prerequisites

  • Python 3.10
  • Selenium library
  • Firefox browser

Setup

Install the Selenium library using pip:

pip install selenium
Enter fullscreen mode Exit fullscreen mode

Steps

  1. Import the necessary libraries

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    
  2. Create a new instance of the Firefox driver

    driver = webdriver.Firefox()
    
  3. Navigate to the YouTube home page

    driver.get("https://www.youtube.com/")
    
  4. Locate the search bar using xpath '//*[@id="search"]'

    search_bar = driver.find_element(By.XPATH, '//*[@id="search"]')
    
  5. Enter a search query

    search_bar.send_keys("《想我就打给我》-Bell玲惠")
    
  6. Press the Enter key to submit the search query

    search_bar.submit()
    
  7. (Optional) Close the browser

    driver.close()
    

By following these steps, you can automate a search on the YouTube website using the Selenium Python module. You can modify the code to search for anything you like, and it can be used as a foundation for more complex automation tasks. The full code can be found here.

Top comments (0)