📜 ⬆️ ⬇️

Selenium for Python. Chapter 3. Navigation

Continuation of the translation of the unofficial Selenium documentation for Python.
The translation was made with the permission of the author Baiju Muthukadan.
The original can be found here .

Content:


1. Installation
2. First Steps
3. Navigation
4. Search for Items
5. Expectations
6. Page Objects
7. WebDriver API
8. Appendix: Frequently Asked Questions

3. Navigation


Presumably, the first thing you want to do with WebDriver is to follow a link. Usually for such purposes use the get method:

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

The driver.get method redirects to the page URL provided in the parameter. WebDriver will wait until the page has completely loaded (that is, the “onload” event is ignored) before transferring control to your test or script. It should be noted that if the page uses a lot of AJAX code when loading, then WebDriver may not recognize whether it has fully loaded. If you need to guarantee the full loading of pages, you can use the waiting (eng. Waits).
')

3.1. Page interaction


The ability to click on the link is not that useful by itself. What you really want to do is interact with the page, or, to be precise, with the HTML elements on the page. First you need to find them. WebDriver provides a number of ways to search for items. For example, on the page there is an element defined as follows:

 <input type="text" name="passwd" id="passwd-id" /> 

It can be found using any of the following methods:

 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 search for the address of the hyperlink in the text of the hyperlink, but be careful: the text must match exactly. Also, be careful when using XPATH in WebDriver. If there is more than one element that meets the conditions of the query, only the first one found will be returned. If nothing is found, a NoSuchElementException will be raised.

WebDriver has an “Object-Oriented” API [Application Programming Interface (English application programming interface) - a set of ready-made methods and properties provided by an application (library, service) for use in external software products. The API allows you to use the functionality of the original application (library, service), without delving into the subtleties of the implementation of this functionality. - Approx. lane]; we represent all element types using the same interface. This means that even though you see a lot of available methods that you can choose when you press the autocomplete key combination in your IDE [Integrated Development Environment, a software system used by programmers to develop software. - Approx. lane.], not all of them will make sense to you or not all will be valid. Do not worry! WebDriver will try to fix everything, so if you call the method using it incorrectly (for example, use “setSelected ()” for the “meta” tag [Meta Tags (English meta tags) - HTML tags designed to provide structured metadata about web page. As a rule, they are indicated in the header of the HTML document. - Note]], WebDriver will raise an exception.

So we got the item. What can you do with it? First of all, you will want to enter some text in the text field:

 element.send_keys("some text") 

You can also simulate pressing the keyboard arrow keys with the “Keys” class:

 element.send_keys(" and some", Keys.ARROW_DOWN) 

The send_keys method can be invoked for any element that allows you to check keyboard shortcuts, such as those used in GMail. There is a side effect that entering into the text field does not automatically clear it. Instead, what you type on the keyboard will be added to the one already entered in the field. Clear textarea text field or text area is easy - using the clear method:

 element.clear() 

3.2. Filling out forms


We have already considered entering text into a text area or text field, but what about other elements? You can try to expand the drop-down list, after which you can use “setSelected” to highlight tags like OPTION. Working with SELECT tags is not so difficult:

 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() 

Such a code will find the first “SELECT” element on the page, and in a loop it will go through all OPTION tags in turn, giving their values ​​and highlighting them one by one.

As you can see, this is not the fastest way to work with SELECT elements. The classes supported by the webdriver contain one called “Select”, it provides more convenient ways to interact:

 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 the ability to deselect all items from the drop-down list:

 select = Select(driver.find_element_by_id('id')) select.deselect_all() 

This code removes the selection from all OPTION tags of the first SELECT tag on the page.

Suppose for a test you need a list of all the default options. The Select class provides this property (returns a list):

 select = Select(driver.find_element_by_xpath("xpath")) all_selected_options = select.all_selected_options 

For all available options use:

 options = select.options 

After completing the form is complete, you probably want to “save” the changes [submit - send, transmit, confirm - Approx. trans.]. One way to do this is to find the “submit” button and click on it:

 # , ID   "submit" :) driver.find_element_by_id("submit").click() 

As an alternative to the first method, you can use the “submit” method, available for each element. If you call it for an element inside a form, WebDriver runs through the entire DOM structure until it finds the closing form tag, and then calls submit for it. If the element is out of shape, then NoSuchElementException will be raised:

 element.submit() 

3.3. Dragging


There are two options for dragging items: moving an item by a certain amount, or dragging it to another item:

 element = driver.find_element_by_name("source") target = driver.find_element_by_name("target") from selenium.webdriver import ActionChains action_chains = ActionChains(driver) action_chains.drag_and_drop(element, target) 

3.4. Switching between windows and frames


Modern web applications rarely do without frames (frame) and rarely when limited to one window. WebDriver supports switching between named windows using the “switch_to_window” method:

 driver.switch_to_window("windowName") 

All calls starting with the driver will now be interpreted as facing the received window. But how do you know the name of the window? Take a look at the javascript code or link that opens the window:

 <a href="_.html" target=""> ,    </a> 

You can also send a window handle to the switch_to_window () method. Using this feature, you can use the loop to iterate through all open windows, for example, like this:

 for handle in driver.window_handles: driver.switch_to_window(handle) 

You can also switch between frames (frame or iframes):

 driver.switch_to_frame("frameName") 

You can access subordinate frames by submitting a path separated by a dot, or you can get a frame by index:

 driver.switch_to_frame("frameName.0.child") 

The following code will redirect to a frame named “child”, which in turn belongs to the first subordinate frame of the frame “frameName”. Paths to the frames are described completely - from the top level :

 driver.switch_to_frame("frameName.0.child") 

When working with frames is complete, you need to switch back to the main frame, which can be done as follows:

 driver.switch_to_default_content() 

3.5. Popup windows


Selenium WebDriver from the package supports the management of pop-up dialog boxes. After you initiate the launch, a window will open, you can manage it like this:

 alert = driver.switch_to_alert() 

The code will return the object of the current open window. With this object, you can accept, reject a window question, read its contents, or even enter text at the window invitation. The interface for interacting with pop-up windows works equally well for both alerts (alerts), and for confirmation requests (confirms) and prompts for prompts. For more information, see the API documentation.

3.6. Navigation: history and location


Earlier, we mentioned navigating a link using the “get” command (driver.get (“ www.example.com ”)). As you may have noticed, WebDriver for some cases provides highly focused, specialized interaction interfaces, and navigation is not an exception. To follow the link, you can use the get method:

 driver.get("http://www.example.com") 

To go forward or backward through the tab history:

 driver.forward() driver.back() 

Keep in mind that this functionality is completely dependent on the driver used. You can get an unexpected result if you are accustomed to the behavior of a particular browser while working with another.

3.7. Cookies


Before we complete this chapter, you may be interested to learn how to use cookies. First of all, you need a domain that uses cookies:

 #     driver.get("http://www.example.com") #  .  cookie     cookie = {"": ""} driver.add_cookie(cookie) #          URL all_cookies = driver.get_cookies() for cookie_name, cookie_value in all_cookies.items(): print("%s -> %s", cookie_name, cookie_value) 


Go to the next chapter.

Source: https://habr.com/ru/post/250947/


All Articles