How To Automate Web Browser Using Python Selenium

When you write an automation test case with python, you always need to test the functions in different web browsers such as Firefox, Chrome, Safari, and IE. Python can help you to do this with the python selenium library. This article will tell you how to configure and start related web browsers in python source code to automate web browsers using python selenium.

1. Make Sure Python Selenium Package Has Been Installed.

  1. Run the command pip show selenium to check whether the python selenium library has been installed on your python environment.
    $ pip show selenium
  2. If the above command returns that the python selenium library does not being installed, you can run the command pip install selenium to install it.
    pip install selenium
  3. Run the command pip show selenium again to verify.
    $ pip show selenium
    Name: selenium
    Version: 3.141.0
    Summary: Python bindings for Selenium
    Home-page: https://github.com/SeleniumHQ/selenium/
    Author: UNKNOWN
    Author-email: UNKNOWN
    License: Apache 2.0
    Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
    Requires: urllib3
    Required-by: 
    

2. Automate Firefox Browser In Selenium Python.

  1. Download related geckodriver from https://github.com/mozilla/geckodriver/releases.
  2. Unzip the download file to a local directory.
  3. Use the below python code to start a Firefox web browser automatically. If you meet any error, you can read the article How To Resolve WebdriverException Geckodriver Executable Needs To Be In Path
    from selenium import webdriver
    import time
    # Pass in the firefox web browser selenium driver save path. 
    browser = webdriver.Firefox(executable_path = '/Users/zhaosong/Documents/WorkSpace/tool/geckodriver')
    browser.get('https://www.google.com') 
    time.sleep(10)
    browser.quit()
    

3. Open Chrome Browser In Selenium Python.

  1. Download related chromedriver from https://sites.google.com/a/chromium.org/chromedriver/
  2. Unzip the chromedriver executable file to a local folder.
  3. Run the below source code to open chrome browser in selenium python.
    import time
    from selenium import webdriver
    # Pass in the google chromedriver executable file save path.
    browser = webdriver.Chrome(executable_path = '/Users/zhaosong/Documents/WorkSpace/tool/chromedriver')
    browser.get('https://www.google.com') 
    time.sleep(10)
    browser.quit()
    

4. Open Internet Explorer In Selenium Python.

  1. Download the python selenium IE driver from the link such as https://selenium-release.storage.googleapis.com/index.html?path=3.9/.
  2. The download file name is something like IEDriverServer_x64_3.9.0.zip.
  3. Unzip the above zip file will create an IEDriverServer.exe file. This is just the python selenium IE driver executable file. Remember its location (for example C:\IEDriverServer.exe).
  4. Write the below python source code in your python program.
    from selenium import webdriver
    # Pass in the selenium IE driver file save path.
    browser = webdriver.Ie("C:\\IEDriverServer.exe")
    browser.get('https://www.google.com') 
    time.sleep(10) 
    browser.quit()
    
  5. When you run the above code in a Windows OS, it will open an Internet Explorer to browse URL https://www.google.com automatically.

5. Automate Safari Browser In Selenium Python.

Safari driver is included with macOS by default, it is saved in folder /usr/bin. You can run the command which safaridriver in the command line to get its saved folder path. So you do not need to download and install the safari driver.

$ which safaridriver
/usr/bin/safaridriver

But before you can open the Safari web browser with python selenium, you need to do the following settings, otherwise, you may encounter the below error message when running your python code.

selenium.common.exceptions.SessionNotCreatedException: Message: Could not create a session: You must enable the ‘Allow Remote Automation’ option in Safari’s Develop menu to control Safari via WebDriver.

5.1 Enable Allow Remote Automation Option In Safari Web Browser.

  1. Open Safari web browser, then click Safari —> Preferences… menu item in the top menu bar.
    macos-safari-preferences-menu-item
  2. Click the Advanced icon in the popup dialog. Check Show Develop menu in menu bar checkbox.
    safari-preferences-advanced-dialog
  3. Then there will display a Develop menu item in the Safari web browser menu bar. Click Develop —> Allow Remote Automation menu item to select it.
    safari-develop-allow-remote-automation-menu-item
  4. Now run the below python code to open the Safari web browser automatically.
    from selenium import webdriver
    import time
    browser = webdriver.Safari(executable_path = '/usr/bin/safaridriver')    
    browser.get('https://www.google.com')
    time.sleep(10)
    browser.quit()
    

6. Automate Web Browsers With Selenium WebDriver In Python Unittest.

  1. Import python built-in unittest module.
  2. Create a python class that extends unittest.TestCase class.
  3. Open web browsers in selenium python in the TestCase class’s setUpClass method.
  4. Use web browsers in TestCase class’s test function ( function browse_page in this example).
  5. Close and quit the web browser in TestCase class’s tearDownClass method.
'''
Created on Aug 31, 2018
@author: zhaosong
'''

from selenium import webdriver
import time
import unittest

class ChromeBrowserTest(unittest.TestCase):

    chrome_browser = None
    page_url = ''

    # Class setup method.
    @classmethod
    def setUpClass(cls):
        ChromeBrowserTest.chrome_browser = webdriver.Chrome(executable_path = '/Users/zhaosong/Documents/WorkSpace/tool/chromedriver')
        print('Safari browser start.')

    # Class teardown method
    @classmethod
    def tearDownClass(cls):
        if(ChromeBrowserTest.chrome_browser!=None):
            ChromeBrowserTest.chrome_browser.quit()
            print('Safari browser quit.')
        else:
            print('Safari browser is not started.')   
    
    # This is the test function.    
    def browse_page(self):
        if(self.chrome_browser!=None and len(self.page_url)>0):
            self.chrome_browser.get(self.page_url)
            print("Safari browser browse page.")
            time.sleep(10)
        else:
            print('Safari browser is not started or page_url is empty.')       

if __name__ == '__main__':
    ChromeBrowserTest.page_url = 'https://www.baidu.com'
    # Create a TestSuite object.
    test_suite = unittest.TestSuite()
    # Add test function in the suite.
    test_suite.addTest(ChromeBrowserTest('browse_page'))
    # Run test suite and get test result.
    testResult = unittest.TestResult()
    test_suite.run(testResult)
    print(testResult)

Reference

  1. Python 3 Unittest Html And Xml Report Example

3 thoughts on “How To Automate Web Browser Using Python Selenium”

  1. I can not find how to open internet explorer in selenium python in your article, can you write that? But other part such as how to open chrome browser in selenium python are very helpful, thank you very much.

Leave a Comment

Your email address will not be published. Required fields are marked *

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