About Lesson
First Selenium Python Script
Step-by-step instructions for writing your first Selenium
Python automation script.
New Script File
Let’s write a simple code. Follow the below steps to create the script.
Launch the Eclipse IDE.
Create a new script file.
File >> New >> File
Â
Give a name to the script file. Python script file should have .py
file extension. Enter the following code in the script and save it.
Script Code
Â
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get('https://example.com')
time.sleep(10)
browser.quit()<br />
Run the Script
Right-click on the script and choose the following option: Run As >> Python Run
Explanation
Let’s understand the script. The first statement
from selenium import webdriver
Â
This will import Selenium Webdriver into the script, allowing you to use Selenium commands in the script. Similarly, import time will allow time commands in the script.
Â
time.sleep(10) will pause the script execution for 10 seconds. This will allow you to see the browser launched by the script. Otherwise, the script will execute quickly and immediately close the browser.
Â
browser = webdriver.Chrome()
Â
The above statement initializes the browser object by creating an instance of the Chrome object. This will create and start a session for browser interaction.
Â
browser.get(‘https://example.com’)
Â
The get() method allows the browser to navigate the specified URL.
Â
browser.quit()
Â
The quit() method closes the browser. This method will close all browser instances, and no more browser commands can be sent to the browser in the script.
Â