Selenium for Python. Chapter 2. First Steps

  • Tutorial
Continued translation of Selenium informal documentation for Python.
Translated with permission from Baiju Muthukadan.
The original can be found here .

Content:


1. Installation
2. First Steps
3. Navigation
4. Finding Elements
5. Expectations
6. Page Objects
7. WebDriver API
8. Application: Frequently Asked Questions

2. First steps


2.1. Simple use


If you have established a Selenium binding to Python, you can start using it with the Python interpreter.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()

The code above can be saved to a file (for example, python_org_search.py), and run:
python python_org_search.py
The Python you run must contain the selenium module installed.

2.2. Step-by-step example analysis


The selenium.webdriver module provides all the functionality of WebDriver. WebDriver currently supports implementations of Firefox, Chrome, Ie, and Remote. The Keys class provides interaction with keyboard commands such as RETURN, F1, ALT, etc ...

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

Next, an element of the Firefox WebDriver class is created.

driver = webdriver.Firefox()

The driver.get method redirects to the page the URL in the parameter. WebDriver will wait until the page has fully loaded (that is, the onload event is ignored) before passing control to your test or script. It is worth noting that if the page uses a lot of AJAX code at loading, then WebDriver may not recognize if it loaded completely:

driver.get("http://www.python.org")

The next line is the assertion that the heading contains the word “Python” [assert allows you to check assumptions about the values ​​of arbitrary data in any place in the program. At its core, assert resembles a statement of fact located in the middle of program code. In cases where the spoken statement is not true, assert throws an exception. This behavior allows you to control the execution of the program in a strictly defined direction. The difference between assert and conditions is that a program with assert does not accept a different course of events, considering further execution of a program or function meaningless - Note. trans.]:

assert "Python" in driver.title

WebDriver provides a number of ways to retrieve elements using the find_element_by_ * methods. For example, the text input element input can be found by its name attribute by the find_element_by_name method. A detailed description of the element search methods can be found in the Element Search chapter:

elem = driver.find_element_by_name("q")

After that, we send keystrokes (similar to entering keys from the keyboard). Special commands can be passed using the Keys class imported from selenium.webdriver.common.keys:

elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)

After the response of the page, you will get the result, if any. To make sure that we get any result, we add the statement:

assert "No results found." not in driver.page_source

Finally, the browser window closes. You can also call the quit method instead of close. The quit method closes the browser completely, while close closes one tab. However, in the case when only one tab is open, by default most browsers close completely:

driver.close()

2.3. Using Selenium to write tests


Selenium is most often used to write test cases. The selenium package itself does not provide any test utilities or development tools. You can write tests using the Python unittest module. Your other choice as test utilities / development tools may be py.test and nose.
In this chapter, unittest will be used as the selected utility. The following is a modified example using this module. This script tests the search functionality on python.org:

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class PythonOrgSearch(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
    def test_search_in_python_org(self):
        driver = self.driver
        driver.get("http://www.python.org")
        self.assertIn("Python", driver.title)
        elem = driver.find_element_by_name("q")
        elem.send_keys("pycon")
        assert "No results found." not in driver.page_source
        elem.send_keys(Keys.RETURN)
    def tearDown(self):
        self.driver.close()
if __name__ == "__main__":
    unittest.main()

You can run the test above from the command line with the following command:
python test_python_org_search.py
.
-------------------------------------------------- --------------------
Ran 1 test in 15.566s
Ok
The result above shows that the test completed successfully.

2.4. Step-by-step example analysis


First, all the basic required modules were imported. The unittest module is built into Python and implemented in Java's JUnit. This module provides a utility for organizing tests.

The selenium.webdriver module provides all the functionality of WebDriver. WebDriver currently supports implementations of Firefox, Chrome, Ie, and Remote. The Keys class provides interaction with keyboard commands such as RETURN, F1, ALT, etc ...

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

Test class inherited from unittest.TestCase. Inheriting the TestCase class is a way of telling unittest that it is a test:

class PythonOrgSearch(unittest.TestCase):

setUp is part of the initialization, this method will be called before each test method that you are going to write inside the test class. Here we create an element of the Firefox WebDriver class.

def setUp(self):
    self.driver = webdriver.Firefox()

The following describes our test method. The test method should always begin with the phrase test. The first line of the method creates a local reference to the driver object created by the setUp method.

def test_search_in_python_org(self):
    driver = self.driver

The driver.get method redirects to the page the URL in the parameter. WebDriver will wait until the page has fully loaded (that is, the onload event is ignored) before passing control to your test or script. It is worth noting that if the page uses a lot of AJAX code at loading, then WebDriver may not recognize if it loaded completely:

driver.get("http://www.python.org")

The next line is the statement that the title contains the word “Python”:

self.assertIn("Python", driver.title)

WebDriver provides a number of ways to retrieve elements using the find_element_by_ * methods. For example, the text input element input can be found by its name attribute by the find_element_by_name method. A detailed description of the element search methods can be found in the Element Search chapter:

elem = driver.find_element_by_name("q")

After that, we send keystrokes (similar to entering keys from the keyboard). Special commands can be passed using the Keys class imported from selenium.webdriver.common.keys:

elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)

After the response of the page, you will get the result, if any. To make sure that we get any result, we add the statement:

assert "No results found." not in driver.page_source

The tearDown method will be called after each test method. This is a method for cleaning operations. The current method implements closing the browser window. You can also call the quit method instead of close. The quit method closes the browser completely, while close closes one tab. However, in the case when only one tab is open, by default most browsers close completely .:

def tearDown(self):
    self.driver.close()

The final code is the standard code insertion for starting the test suite [Comparing __name__ with "__main__" means that the module (program file) is launched as a separate program ("main" (English) - "main", "main") (and not imported from another module). If you import a module, the module attribute __name__ will be equal to the file name without a directory and extension - Note trans.]:

if __name__ == "__main__":
    unittest.main()

2.5. Using Selenium with remote WebDriver


To use remote WebDriver (remote web driver), you must run the Selenium server. To start the server, use the command:
java -jar selenium-server-standalone-2.xxjar
While the Selenium server is starting up, you can see messages like:
15:43: 07.541 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
The line above reports that you can use the specified URL to connect remote WebDriver. The following are a few examples:

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
driver = webdriver.Remote(
   command_executor='http://127.0.0.1:4444/wd/hub',
   desired_capabilities=DesiredCapabilities.CHROME)
driver = webdriver.Remote(
   command_executor='http://127.0.0.1:4444/wd/hub',
   desired_capabilities=DesiredCapabilities.OPERA)
driver = webdriver.Remote(
   command_executor='http://127.0.0.1:4444/wd/hub',
   desired_capabilities=DesiredCapabilities.HTMLUNITWITHJS)

The variable desired_capabilities is a dictionary. Instead of using the default dictionaries, you can explicitly specify the values:

driver = webdriver.Remote(
   command_executor='http://127.0.0.1:4444/wd/hub',
   desired_capabilities={'browserName': 'htmlunit',
                         'version': '2',
                        'javascriptEnabled': True})

Go to next chapter

Also popular now: