This activity involves automating a simple web interaction using Selenium. In this case, we’ll perform the following tasks:
- Open a Web Browser (Firefox in this case).
- Navigate to the Python Website (
https://www.python.org
). - Print the Page Title.
- Close the Browser after a brief wait.
Prerequisites
- Python is installed. Download Python: https://www.python.org/downloads/
- Install Selenium Library.
- Download GeckoDriver (compatible with Firefox) from:
https://github.com/mozilla/geckodriver/releases Extract the downloaded file and Add it to the system PATH or Place it in the same directory as your script.
To run Selenium Python Tests here are the steps to follow:
Import Necessary Librarie
from selenium import webdriver
import time
webdriver
: This module provides the tools to control web browsers using Selenium.
time
: Standard Python library used to introduce pauses in the script .
Initialize the Firefox Driver
driver = webdriver.Firefox()
It Initializes a new instance of the Firefox browser using GeckoDriver so Selenium launches a Firefox browser window and now the script can now send commands to control the browser.
Open the Python website
driver.get("https://www.python.org")
Here Use the .get() method to navigate to a website. This method waits for the page to load completely the browser navigates to the given URL and the page loads fully before the script proceeds to the next command.
Check the Page Title
print(driver.title)
It prints the title of the current web page to the console.
Close the Browser window
time.sleep(5)
driver.close()
The sleep method pauses the script for 5 seconds to allow you to see the search results before the browser closes.
Summary :
Here is the complete script for your first Selenium test in Python.
from selenium import webdriver
import time
# Create a new instance of the Firefox driver (GeckoDriver)
driver = webdriver.Firefox()
# Open the Python website
driver.get("https://www.python.org")
# Print the page title
print(driver.title)
# Close the browser window
time.sleep(5) # Wait for 5 seconds before closing the browser
driver.close()
Once you run the script, the Firefox browser will open and navigate to the given URL and then prints the page title in the console.
With this you have created your first script for Selenium using Python.