First Script-Selenium With Python

We are now in a good position to get started with the our first script. Open up PyCharm (or your IDE) and create first script, where we will be opening Google’s search page in Firefox.


from selenium import webdriver

driver=webdriver.Firefox()
driver.implicitly_wait(20)
driver.maximize_window()

driver.get('http://www.google.com')

driver.quit()

Save this as firstscript.py. Now it’s time to run the script.

Running Our First Script

If you’re using a Text Editor like the Sublime Editor, then follow these steps :

Open Terminal with Ctrl +Alt+ T.

Go to the folder where the created script is kept. For me it is /Documents/SeleniumPy.

Run the script as python scriptname.py

Screenshot from 2015-06-17 18:17:36

You’ll see the Firefox browser pop-up and then Google’s home page coming up. This is our target. We have achieved it. Mission Accomplished!!

Screenshot from 2015-06-17 18:17:25

If, you’re using an IDE, like PyCharm, then go to the RUN option at the top. Click on it.

Screenshot from 2015-07-09 18:42:29

Select the second one, as that is your test script’s name. The next screen will appear like this

Screenshot from 2015-07-09 18:42:48

And then, the browser window will come up and you’ll get the google home page

Understanding the Script

So we were successful in the creation of scripts using Selenium and Python. Now it’s time to understand how this worked actually.

from selenium import webdriver

The first line calls the Selenium bindings into the script, i.e. the webdriver bindings which are to be utilized.

driver=webdriver.Firefox()

Using this, we create the Firefox instance of Selenium webdriver.

driver.implicitly_wait(20)

Next line is an implicit wait for 20 seconds. This we will talk more about when we will implement webdriver waits.

driver.maximize_window()

Next we are maximizing the browser window.

driver.get('http://www.google.com')

Now we will browse to the website we want to go. The driver.get method will navigate to a page given by the URL. WebDriver will wait until the page has fully loaded (that is, the “onload” event has fired) before returning control to your test or script.

driver.quit()

The quit () method is one which will close the instance of the browser and exit it.

The above example is an example of script with Firefox. To see how we can run a script on Google chrome, click here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.