Writing Your First Selenium Script in Python
Writing Your First Selenium Script in Python
Selenium is a popular tool for automating web browsers. It allows you to write scripts that can interact with websites just like a real user — clicking buttons, filling forms, and verifying content. Here’s a simple step-by-step guide to write your first Selenium script using Python.
Step 1: Set Up Your Environment
Install Python
Make sure Python is installed on your machine. You can download it from python.org.
Install Selenium Package
Open your terminal or command prompt and run:
bash
Copy
Edit
pip install selenium
Download WebDriver
Selenium needs a WebDriver to control the browser. For example:
ChromeDriver for Google Chrome
GeckoDriver for Firefox
Download the appropriate WebDriver and place it in a folder included in your system’s PATH or note its location for use in the script.
Step 2: Write Your First Selenium Script
Here’s a simple example that opens a browser, navigates to Google, searches for "Selenium Python," and prints the page title.
python
Copy
Edit
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
# Set up the WebDriver (change the path to your WebDriver if needed)
driver = webdriver.Chrome(executable_path='path/to/chromedriver')
# Open Google
driver.get('https://www.google.com')
# Find the search box using its name attribute value
search_box = driver.find_element(By.NAME, 'q')
# Type the search query
search_box.send_keys('Selenium Python')
# Press Enter
search_box.send_keys(Keys.RETURN)
# Wait for 3 seconds to see results (optional)
time.sleep(3)
# Print the page title
print(driver.title)
# Close the browser
driver.quit()
Step 3: Run Your Script
Save the above code in a file named first_selenium_script.py.
Run it from the terminal:
bash
Copy
Edit
python first_selenium_script.py
Your Chrome browser will open, search on Google, and then close after printing the page title.
Step 4: Understand the Code
webdriver.Chrome() initializes the Chrome browser.
get() navigates to the specified URL.
find_element() locates HTML elements on the page.
send_keys() sends keystrokes to an element.
Keys.RETURN simulates pressing the Enter key.
time.sleep() pauses execution so you can see results.
quit() closes the browser.
Next Steps
Explore locating elements by different methods (ID, CSS_SELECTOR, XPATH).
Add waits to handle dynamic content.
Automate more complex user interactions.
Learn Selenium Python Training in Hyderabad
Read More
Installing Selenium WebDriver in Python: A Quick Guide
Why Use Python for Selenium Automation?
What is Selenium? A Beginner’s Guide for Python Developers
Comparing Selenium with Python vs Selenium with Java: Which One to Choose?
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment