First Selenium Webdriver Script : Python Code

Selenium supports cross-browser testing which means we can automate other browsers like Firefox, Internet Explorer, Google Chrome, Safari and headless browsers like HTMLUnit driver and PhantomJS.

     How to run your scripts in Firefox Browser.
you will learn how to execute your selenium script with python for Firefox browser

Scenario :
Invoke Firefox browser.
Enter UserName and Password
Click on the Login button.
Verify the Window Title
Close the browser

Precondition : you should download the gecko driver by selecting the appropriate version of your browser
Script:
from selenium import webdriver
FFPath="C:\\Softwares\\BrowserDrivers\\FF\\geckodriver-v0.24.0-win64\\geckodriver.exe"
driver=webdriver.Firefox(executable_path=FFPath)
driver.get("http://newtours.demoaut.com")
driver.find_element_by_name("userName").send_keys("hello")
driver.find_element_by_name("password").send_keys("hello")
driver.find_element_by_name("login").click()
print(driver.title)
driver.close()

the above script save it as python_Login.py
How to run the script in IDE PyCharm.
              Select the python file and right click on mouse then click on Run
                 



Or click on Right Top corner of the IDE

How to Execute your script from Command line
1)   Navigate to where your python is installed
2)   Type below command
Ex:
C:\python\pythonLatest> Python python_Login.py(here you should give where your file is located) 

Explaining about script
In Python, import statements are used to import the modules present in another packages. In simple words, import keyword is used to import built-in and user-defined modules  into your source file.

from selenium import webdriver - References the WebDriver interface which is required to instantiate a new web browser.

Set the Gecko Driver Path
FFPath="C:\\Softwares\\BrowserDrivers\\FF\\geckodriver-v0.24.0-win64\\geckodriver.exe"

A driver object is instantiated through:
driver=webdriver.Firefox(executable_path=FFPath)

The driver.get method will navigate to a page given by the URL. WebDriver will wait until the page has fully loaded.

driver.get("http://newtours.demoaut.com")

WebDriver find elements in application in number of ways.

For example, the input text element can be located by its name attribute using find_element_by_name method. We will discuss in detail in the Locating Elements session.

driver.find_element_by_name("userName").send_keys("hello")
driver.find_element_by_name("password").send_keys("hello")
driver.find_element_by_name("login").click()

It will  print the title of the page.
print(driver.title)

Last line is the browser window is closed. You can use quit method instead of close. The quit will exit entire browser/driver session whereas close will close active browser.


driver.close()/driver.quit()


Comments