3.Navigating¶
The first thing you’ll want to do with WebDriver is navigate to a link. Thenormal way to do this is by callingget method:
driver.get("http://www.google.com")
WebDriver will wait until the page has fully loaded (that is, theonloadevent has fired) before returning control to your test or script.Be awarethat if your page uses a lot of AJAX on load then WebDriver may not know when ithas completely loaded. If you need to ensure such pages are fully loaded thenyou can usewaits.
3.1.Interacting with the page¶
Just being able to go to places isn’t terribly useful. What we’d really like todo is to interact with the pages, or, more specifically, the HTML elementswithin a page. First of all, we need to find one. WebDriver offers a number ofways to find elements. For example, given an element defined as:
<inputtype="text"name="passwd"id="passwd-id"/>
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']")element=driver.find_element(By.CSS_SELECTOR,"input#passwd-id")
You can also look for a link by its text, but be careful! The text must be anexact match! You should also be careful when usingXPATH in WebDriver. Ifthere’s more than one element that matches the query, then only the first willbe returned. If nothing can be found, aNoSuchElementException will beraised.
WebDriver has an “Object-based” API; we represent all types of elements usingthe same interface. This means that although you may see a lot of possiblemethods 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 willattempt 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.
So, you’ve got an element. What can you do with it? First of all, you may wantto 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 callsend_keys on any element, which makes it possible totest keyboard shortcuts such as those used on GMail. A side-effect of this isthat 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 clearthe contents of a text field or textarea with theclear method:
element.clear()
3.2.Filling in forms¶
We’ve already seen how to enter text into a textarea or text field, but whatabout the other elements? You can “toggle” the state of the drop down, and youcan use “setSelected” to set something like anOPTION tag selected. DealingwithSELECT tags isn’t too bad:
element=driver.find_element(By.XPATH,"//select[@name='name']")all_options=element.find_elements(By.TAG_NAME,"option")foroptioninall_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 ofits 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 SELECTelements. WebDriver’s support classes include one called a “Select”, whichprovides useful methods for interacting with these:
fromselenium.webdriver.support.uiimportSelectselect=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, Selectclass 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
Once you’ve finished filling out the form, you probably want to submit it. Oneway to do this would be to find the “submit” button and click it:
# Assume the button has the ID "submit" :)driver.find_element(By.ID,"submit").click()
Alternatively, WebDriver has the convenience method “submit” on every element.If you call this on an element within a form, WebDriver will walk up the DOMuntil it finds the enclosing form and then calls submit on that. If the elementisn’t in a form, then theNoSuchElementException will be raised:
element.submit()
3.3.Drag and drop¶
You can use drag and drop, either moving an element by a certain amount, or onto another element:
element=driver.find_element(By.NAME,"source")target=driver.find_element(By.NAME,"target")fromselenium.webdriverimportActionChainsaction_chains=ActionChains(driver)action_chains.drag_and_drop(element,target).perform()
3.4.Moving between windows and frames¶
It’s rare for a modern web application not to have any frames or to beconstrained to a single window. WebDriver supports moving between named windowsusing the “switch_to.window” method:
driver.switch_to.window("windowName")
All calls todriver will now be interpreted as being directed to theparticular window. But how do you know the window’s name? Take a look at thejavascript or link that opened it:
<ahref="somewhere.html"target="windowName">Clickheretoopenanewwindow</a>
Alternatively, you can pass a “window handle” to the “switch_to.window()”method. Knowing this, it’s possible to iterate over every open window like so:
forhandleindriver.window_handles:driver.switch_to.window(handle)
You can also swing from frame to frame (or into iframes):
driver.switch_to.frame("frameName")
It’s possible to access subframes by separating the path with a dot, and you canspecify the frame by its index too. That is:
driver.switch_to.frame("frameName.0.child")
would go to the frame named “child” of the first subframe of the frame called“frameName”.All frames are evaluated as if from *top*.
Once we are done with working on frames, we will have to come back to the parentframe which can be done using:
driver.switch_to.default_content()
3.5.Popup dialogs¶
Selenium WebDriver has built-in support for handling popup dialog boxes. Afteryou’ve triggered action that would open a popup, you can access the alert withthe following:
alert=driver.switch_to.alert
This will return the currently open alert object. With this object, you can nowaccept, dismiss, read its contents or even type into a prompt. This interfaceworks equally well on alerts, confirms, prompts. Refer to the API documentationfor more information.
3.6.Navigation: history and location¶
Earlier, we covered navigating to a page using the “get” command (driver.get("http://www.example.com")). As you’ve seen, WebDriver has anumber of smaller, task-focused interfaces, and navigation is a useful task. Tonavigate to a page, you can useget method:
driver.get("http://www.example.com")
To move backward and forward in your browser’s history:
driver.forward()driver.back()
Please be aware that this functionality depends entirely on the underlyingdriver. It’s just possible that something unexpected may happen when you callthese methods if you’re used to the behavior of one browser over another.
3.7.Cookies¶
Before moving to the next section of the tutorial, you may be interested inunderstanding how to use cookies. First of all, you need to be on the domainthat the cookie will be valid for:
# Go to the correct domaindriver.get("http://www.example.com")# Now set the cookie. This one's valid for the entire domaincookie={'name':'foo','value':'bar'}driver.add_cookie(cookie)# And now output all the available cookies for the current URLdriver.get_cookies()
