Writing Your First Selenium Automation Script in Python
Selenium is one of the most popular tools for automating web browsers. With Python, it becomes even more accessible for beginners and professionals alike. In this blog, we’ll walk you through writing your first Selenium automation script using Python — from installation to execution.
What is Selenium?
Selenium is an open-source tool used to automate web browsers. It allows testers and developers to simulate user actions such as clicking, typing, navigating pages, and verifying content. It supports multiple languages, including Python, Java, and C#.
Installing Selenium for Python
Before writing the script, you need to install the Selenium package. You can do this easily using pip:
bash
Copy
Edit
pip install selenium
You’ll also need a WebDriver, like ChromeDriver or GeckoDriver, which allows Selenium to interact with a specific browser.
Download ChromeDriver from: https://chromedriver.chromium.org
Make sure it's in your system's PATH or specify the path in your script.
Writing Your First Script
Here's a simple script that opens Google, searches for "Selenium Python", and prints the title of the results page.
python
Copy
Edit
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
# Initialize the Chrome WebDriver
driver = webdriver.Chrome()
# Open Google
driver.get("https://www.google.com")
# Find the search box using name attribute
search_box = driver.find_element(By.NAME, "q")
# Type in the search query
search_box.send_keys("Selenium Python")
# Press ENTER
search_box.send_keys(Keys.RETURN)
# Wait for results to load
time.sleep(2)
# Print the page title
print("Page Title:", driver.title)
# Close the browser
driver.quit()
Understanding the Script
webdriver.Chrome() launches the browser.
driver.get() opens the desired URL.
find_element() locates the input field using the element’s attributes.
send_keys() simulates typing and pressing keys.
time.sleep() adds delay for the results to load (though using WebDriverWait is more reliable in advanced scripts).
driver.quit() closes the browser.
Next Steps
- Now that you've written your first script, you can explore:
- Clicking buttons and links
- Extracting text or elements
- Filling forms
- Handling pop-ups and alerts
- Waiting for elements with WebDriverWait
Conclusion
Creating your first Selenium automation script in Python is a great starting point for automating repetitive browser tasks or building a foundation for web testing. With just a few lines of code, you can control the browser like a real user. As you continue learning, Selenium’s powerful features will help you build more advanced and reliable automation scripts.
Learn Selenium Python Training in Hyderabad
Read More:
Selenium with Python: Using XPath and CSS Selectors
Visit our IHub Talent Training Institute
Comments
Post a Comment