Docsity

Guia Biblioteca Selenium, Traduções de Informática

Pré-visualização parcial do texto

Baixe Guia Biblioteca Selenium e outras Traduções em PDF para Informática, somente na Docsity!

Selenium Python Bindings

Release 2

Baiju Muthukadan

Nov 07, 2018

  • 1 Installation
    • 1.1 Introduction
    • 1.2 Downloading Python bindings for Selenium
    • 1.3 Drivers
    • 1.4 Detailed instructions for Windows users
    • 1.5 Downloading Selenium server
  • 2 Getting Started
    • 2.1 Simple Usage
    • 2.2 Example Explained
    • 2.3 Using Selenium to write tests
    • 2.4 Walk through of the example
    • 2.5 Using Selenium with remote WebDriver
  • 3 Navigating
    • 3.1 Interacting with the page
    • 3.2 Filling in forms
    • 3.3 Drag and drop
    • 3.4 Moving between windows and frames
    • 3.5 Popup dialogs
    • 3.6 Navigation: history and location
    • 3.7 Cookies
  • 4 Locating Elements
    • 4.1 Locating by Id
    • 4.2 Locating by Name
    • 4.3 Locating by XPath
    • 4.4 Locating Hyperlinks by Link Text
    • 4.5 Locating Elements by Tag Name
    • 4.6 Locating Elements by Class Name
    • 4.7 Locating Elements by CSS Selectors
  • 5 Waits
    • 5.1 Explicit Waits
    • 5.2 Implicit Waits
  • 6 Page Objects
    • 6.1 Test case
    • 6.2 Page object classes
    • 6.3 Page elements
    • 6.4 Locators
  • 7 WebDriver API
    • 7.1 Exceptions
    • 7.2 Action Chains
    • 7.3 Alerts
    • 7.4 Special Keys
    • 7.5 Locate elements By
    • 7.6 Desired Capabilities
    • 7.7 Touch Actions
    • 7.8 Proxy
    • 7.9 Utilities
    • 7.10 Service
    • 7.11 Application Cache
    • 7.12 Firefox WebDriver
    • 7.13 Firefox WebDriver Options
    • 7.14 Firefox WebDriver Profile
    • 7.15 Firefox WebDriver Binary
    • 7.16 Firefox WebDriver Extension Connection
    • 7.17 Chrome WebDriver
    • 7.18 Chrome WebDriver Options
    • 7.19 Chrome WebDriver Service
    • 7.20 Remote WebDriver
    • 7.21 Remote WebDriver WebElement
    • 7.22 Remote WebDriver Command
    • 7.23 Remote WebDriver Error Handler
    • 7.24 Remote WebDriver Mobile
    • 7.25 Remote WebDriver Remote Connection
    • 7.26 Remote WebDriver Utils
    • 7.27 Internet Explorer WebDriver
    • 7.28 Android WebDriver
    • 7.29 Opera WebDriver
    • 7.30 PhantomJS WebDriver
    • 7.31 PhantomJS WebDriver Service
    • 7.32 Safari WebDriver
    • 7.33 Safari WebDriver Service
    • 7.34 Select Support
    • 7.35 Wait Support
    • 7.36 Color Support
    • 7.37 Event Firing WebDriver Support
    • 7.38 Abstract Event Listener Support
    • 7.39 Expected conditions Support
  • 8 Appendix: Frequently Asked Questions
    • 8.1 How to use ChromeDriver?
    • 8.2 Does Selenium 2 support XPath 2.0?
    • 8.3 How to scroll down to the bottom of a page?
    • 8.4 How to auto save files using custom Firefox profile?
    • 8.5 How to upload files into file inputs?
    • 8.6 How to use firebug with Firefox?
    • 8.7 How to take screenshot of the current window?

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.

  1. Install Python 3.6 using the MSI available in python.org download page.
  2. Start a command prompt using the cmd.exe program and run the pip command as given below to install selenium.

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

CHAPTER 2

Getting Started

2.1 Simple Usage

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.

2.2 Example Explained

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

CHAPTER 3

Navigating

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.

3.1 Interacting with the page

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