




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































9 Indices and tables 99
Python Module Index 101
iii
Selenium Python Bindings, Release 2
Author Baiju Muthukadan License This document is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Note: This is not an official documentation. If you would like to contribute to this documentation, you can fork this project in Github and send pull requests. You can also send your feedback to my email: baiju.m.mail AT gmail DOT com. So far 40+ community members have contributed to this project (See the closed pull requests). I encourage contributors to add more sections and make it a good documentation!
Contents 1
Selenium Python Bindings, Release 2
2 Contents
Selenium Python Bindings, Release 2
Other supported browsers will have their own drivers available. Links to some of the more popular browser drivers follow.
Chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads Edge: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/ Firefox: https://github.com/mozilla/geckodriver/releases Safari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/
1.4 Detailed instructions for Windows users
Note: You should have an internet connection to perform this installation.
C:\Python35\Scripts\pip.exe install selenium
Now you can run your test scripts using Python. For example, if you have created a Selenium based script and saved it inside C:\my_selenium_script.py, you can run it like this:
C:\Python35\python.exe C:\my_selenium_script.py
1.5 Downloading Selenium server
Note: The Selenium server is only required if you want to use the remote WebDriver. See the Using Selenium with remote WebDriver section for more details. If you are a beginner learning Selenium, you can skip this section and proceed with next chapter.
Selenium server is a Java program. Java Runtime Environment (JRE) 1.6 or newer version is recommended to run Selenium server.
You can download Selenium server 2.x from the download page of selenium website. The file name should be some- thing like this: selenium-server-standalone-2.x.x.jar. You can always download the latest 2.x version of Selenium server.
If Java Runtime Environment (JRE) is not installed in your system, you can download the JRE from the Oracle website. If you are using a GNU/Linux system and have root access in your system, you can also use your operating system instructions to install JRE.
If java command is available in the PATH (environment variable), you can start the Selenium server using this com- mand:
java -jar selenium-server-standalone-2.x.x.jar
Replace 2.x.x with the actual version of Selenium server you downloaded from the site.
4 Chapter 1. Installation
Selenium Python Bindings, Release 2
If JRE is installed as a non-root user and/or if it is not available in the PATH (environment variable), you can type the relative or absolute path to the java command. Similarly, you can provide a relative or absolute path to Selenium server jar file. Then, the command will look something like this:
/path/to/java -jar /path/to/selenium-server-standalone-2.x.x.jar
1.5. Downloading Selenium server 5
If you have installed Selenium Python bindings, you can start using it from Python like this.
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.clear() elem.send_keys("pycon") elem.send_keys(Keys.RETURN) assert "No results found." not in driver.page_source driver.close()
The above script can be saved into a file (eg:- python_org_search.py), then it can be run like this:
python python_org_search.py
The python which you are running should have the selenium module installed.
The selenium.webdriver module provides all the WebDriver implementations. Currently supported WebDriver imple- mentations are Firefox, Chrome, IE and Remote. The Keys class provide keys in the keyboard like RETURN, F1, ALT etc.
from selenium import webdriver from selenium.webdriver.common.keys import Keys
Selenium Python Bindings, Release 2
Next, the instance of Firefox WebDriver is created.
driver = webdriver.Firefox()
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. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded.:
driver.get("http://www.python.org")
The next line is an assertion to confirm that title has “Python” word in it:
assert "Python" in driver.title
WebDriver offers a number of ways to find elements using one of the find_element_by_* methods. For example, the input text element can be located by its name attribute using find_element_by_name method. A detailed explanation of finding elements is available in the Locating Elements chapter:
elem = driver.find_element_by_name("q")
Next, we are sending keys, this is similar to entering keys using your keyboard. Special keys can be sent using Keys class imported from selenium.webdriver.common.keys. To be safe, we’ll first clear any pre-populated text in the input field (e.g. “Search”) so it doesn’t affect our search results:
elem.clear() elem.send_keys("pycon") elem.send_keys(Keys.RETURN)
After submission of the page, you should get the result if there is any. To ensure that some results are found, make an assertion:
assert "No results found." not in driver.page_source
Finally, the browser window is closed. You can also call quit method instead of close. The quit will exit entire browser whereas close‘ will close one tab, but if just one tab was open, by default most browser will exit entirely.:
driver.close()
2.3 Using Selenium to write tests
Selenium is mostly used for writing test cases. The selenium package itself doesn’t provide a testing tool/framework. You can write test cases using Python’s unittest module. The other options for a tool/framework are py.test and nose.
In this chapter, we use unittest as the framework of choice. Here is the modified example which uses unittest module. This is a test for python.org search functionality:
import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys
class PythonOrgSearch (unittest.TestCase):
def setUp(self): self.driver = webdriver.Firefox()
(continues on next page)
8 Chapter 2. Getting Started
Selenium Python Bindings, Release 2
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. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded.:
driver.get("http://www.python.org")
The next line is an assertion to confirm that title has “Python” word in it:
self.assertIn("Python", driver.title)
WebDriver offers a number of ways to find elements using one of the find_element_by_* methods. For example, the input text element can be located by its name attribute using find_element_by_name method. Detailed explanation of finding elements is available in the Locating Elements chapter:
elem = driver.find_element_by_name("q")
Next, we are sending keys, this is similar to entering keys using your keyboard. Special keys can be send using Keys class imported from selenium.webdriver.common.keys:
elem.send_keys("pycon") elem.send_keys(Keys.RETURN)
After submission of the page, you should get the result as per search if there is any. To ensure that some results are found, make an assertion:
assert "No results found." not in driver.page_source
The tearDown method will get called after every test method. This is a place to do all cleanup actions. In the current method, the browser window is closed. You can also call quit method instead of close. The quit will exit the entire browser, whereas close will close a tab, but if it is the only tab opened, by default most browser will exit entirely.:
def tearDown(self): self.driver.close()
Final lines are some boiler plate code to run the test suite:
if name == "main": unittest.main()
2.5 Using Selenium with remote WebDriver
To use the remote WebDriver, you should have Selenium server running. To run the server, use this command:
java -jar selenium-server-standalone-2.x.x.jar
While running the Selenium server, you could see a message looking like this:
15:43:07.541 INFO - RemoteWebDriver instances should connect to: http://127.0.0. ˓→1:4444/wd/hub
The above line says that you can use this URL for connecting to remote WebDriver. Here are some examples:
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities (continues on next page)
10 Chapter 2. Getting Started
Selenium Python Bindings, Release 2
(continued from previous page)
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 desired capabilities is a dictionary, so instead of using the default dictionaries, you can specify the values explic- itly:
driver = webdriver.Remote( command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities={'browserName': 'htmlunit', 'version': '2', 'javascriptEnabled': True })
2.5. Using Selenium with remote WebDriver 11
The first thing you’ll want to do with WebDriver is navigate to a link. The normal way to do this is by calling get method:
driver.get("http://www.google.com")
WebDriver will wait until the page has fully loaded (that is, the onload event has fired) before returning control to your test or script. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded. If you need to ensure such pages are fully loaded then you can use waits.
Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. First of all, we need to find one. WebDriver offers a number of ways to find elements. For example, given an element defined as:
you could find it using any of:
element = driver.find_element_by_id("passwd-id") element = driver.find_element_by_name("passwd") element = driver.find_element_by_xpath("//input[@id='passwd-id']")
You can also look for a link by its text, but be careful! The text must be an exact match! You should also be careful when using XPATH in WebDriver. If there’s more than one element that matches the query, then only the first will be returned. If nothing can be found, a NoSuchElementException will be raised.
WebDriver has an “Object-based” API; we represent all types of elements using the same interface. This means that although you may see a lot of possible methods you could invoke when you hit your IDE’s auto-complete key combination, not all of them will make sense or be valid. Don’t worry! WebDriver will attempt to do the Right Thing, and if you call a method that makes no sense (“setSelected()” on a “meta” tag, for example) an exception will be raised.
Selenium Python Bindings, Release 2
So, you’ve got an element. What can you do with it? First of all, you may want to enter some text into a text field:
element.send_keys("some text")
You can simulate pressing the arrow keys by using the “Keys” class:
element.send_keys(" and some", Keys.ARROW_DOWN)
It is possible to call send_keys on any element, which makes it possible to test keyboard shortcuts such as those used on GMail. A side-effect of this is that typing something into a text field won’t automatically clear it. Instead, what you type will be appended to what’s already there. You can easily clear the contents of a text field or textarea with the clear method:
element.clear()
3.2 Filling in forms
We’ve already seen how to enter text into a textarea or text field, but what about the other elements? You can “toggle” the state of the drop down, and you can use “setSelected” to set something like an OPTION tag selected. Dealing with SELECT tags isn’t too bad:
element = driver.find_element_by_xpath("//select[@name='name']") all_options = element.find_elements_by_tag_name("option") for option in all_options: print("Value is: %s" % option.get_attribute("value")) option.click()
This will find the first “SELECT” element on the page, and cycle through each of its OPTIONs in turn, printing out their values, and selecting each in turn.
As you can see, this isn’t the most efficient way of dealing with SELECT elements. WebDriver’s support classes include one called a “Select”, which provides useful methods for interacting with these:
from selenium.webdriver.support.ui import Select select = Select(driver.find_element_by_name('name')) select.select_by_index(index) select.select_by_visible_text("text") select.select_by_value(value)
WebDriver also provides features for deselecting all the selected options:
select = Select(driver.find_element_by_id('id')) select.deselect_all()
This will deselect all OPTIONs from that particular SELECT on the page.
Suppose in a test, we need the list of all default selected options, Select class provides a property method that returns a list:
select = Select(driver.find_element_by_xpath("//select[@name='name']")) all_selected_options = select.all_selected_options
To get all available options:
options = select.options
14 Chapter 3. Navigating