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:

  1. 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.

1.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:

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

you could find it using any of:

  1. element = driver.find_element_by_id("passwd-id")
  2. element = driver.find_element_by_name("passwd")
  3. 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.

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:

  1. element.send_keys("some text")

You can simulate pressing the arrow keys by using the “Keys” class:

  1. 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 clear method:

  1. element.clear()

1.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 drop down, and you can use “setSelected” to set something like an OPTION tag selected. Dealing with SELECT tags isn’t too bad:

  1. element = driver.find_element_by_xpath("//select[@name='name']")
  2. all_options = element.find_elements_by_tag_name("option")
  3. for option in all_options:
  4. print("Value is: %s" % option.get_attribute("value"))
  5. option.click()

This will find the first “SELECT” element on the page, and cycle through each of it’s 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 “Select”, which provides useful methods for interacting with these:

  1. from selenium.webdriver.support.ui import Select
  2. select = Select(driver.find_element_by_name('name'))
  3. select.select_by_index(index)
  4. select.select_by_visible_text("text")
  5. select.select_by_value(value)

WebDriver also provides features for deselecting all the selected options:

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

This will deselect all OPTIONs from the first 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:

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

To get all available options:

  1. options = select.options

Once you’ve finished filling out the form, you probably want to submit it. One way to do this would be to find the “submit” button and click it:

  1. # Assume the button has the ID "submit" :)
  2. 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 DOM until it finds the enclosing form and then calls submit on that. If the element isn’t in a form, then the NoSuchElementException will be raised:

  1. element.submit()

1.3. Drag and drop

You can use drag and drop, either moving an element by a certain amount, or on to another element:

  1. element = driver.find_element_by_name("source")
  2. target = driver.find_element_by_name("target")
  3.  
  4. from selenium.webdriver import ActionChains
  5. action_chains = ActionChains(driver)
  6. action_chains.drag_and_drop(element, target).perform()

1.4. Moving between windows and frames

It’s rare for a modern web application not to have any frames or to be constrained to a single window. WebDriver supports moving between named windows using the “switch_to_window” method:

  1. driver.switch_to_window("windowName")

All calls to driver will now be interpreted as being directed to the particular window. But how do you know the window’s name? Take a look at the javascript or link that opened it:

  1. <a href="somewhere.html" target="windowName">Click here to open a new window</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:

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

You can also swing from frame to frame (or into iframes):

  1. driver.switch_to_frame("frameName")

It’s possible to access subframes by separating the path with a dot, and you can specify the frame by its index too. That is:

  1. 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 parent frame which can be done using:

  1. driver.switch_to_default_content()

1.5. Popup dialogs

Selenium WebDriver has built-in support for handling popup dialog boxes. After you’ve triggerd action that would open a popup, you can access the alert with the following:

  1. alert = driver.switch_to_alert()

This will return the currently open alert object. With this object you can now accept, dismiss, read its contents or even type into a prompt. This interface works equally well on alerts, confirms, prompts. Refer to the API documentation for more information.

1.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 a number of smaller, task-focused interfaces, and navigation is a useful task. To navigate to a page, you can use get method:

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

To move backwards and forwards in your browser’s history:

  1. driver.forward()
  2. driver.back()

Please be aware that this functionality depends entirely on the underlying driver. It’s just possible that something unexpected may happen when you call these methods if you’re used to the behaviour of one browser over another.

1.7. Cookies

Before we leave these next steps, you may be interested in understanding how to use cookies. First of all, you need to be on the domain that the cookie will be valid for:

  1. # Go to the correct domain
  2. driver.get("http://www.example.com")
  3.  
  4. # Now set the cookie. This one's valid for the entire domain
  5. cookie = {‘name : foo’, value : bar’}
  6. driver.add_cookie(cookie)
  7.  
  8. # And now output all the available cookies for the current URL
  9. driver.get_cookies()

selenium-Navigating的更多相关文章

  1. <译>Selenium Python Bindings 3 - Navigating

    当你想要通过webdriver导航到一个链接,正常的方式点是通过调用get方法: driver.get("http://www.google.com") Interacting w ...

  2. Python爬虫小白入门(四)PhatomJS+Selenium第一篇

    一.前言 在上一篇博文中,我们的爬虫面临着一个问题,在爬取Unsplash网站的时候,由于网站是下拉刷新,并没有分页.所以不能够通过页码获取页面的url来分别发送网络请求.我也尝试了其他方式,比如下拉 ...

  3. 转:SELENIUM TIPS: CSS SELECTORS

    This page will show you some CSS rules and pseudo-classes that will help you move your XPATH locator ...

  4. Python开发爬虫之动态网页抓取篇:爬取博客评论数据——通过Selenium模拟浏览器抓取

    区别于上篇动态网页抓取,这里介绍另一种方法,即使用浏览器渲染引擎.直接用浏览器在显示网页时解析 HTML.应用 CSS 样式并执行 JavaScript 的语句. 这个方法在爬虫过程中会打开一个浏览器 ...

  5. Selenium Navigation

    Navigating Navigate a link with WebDriver: driver.get("http://www.google.com") 1.Interacti ...

  6. 使用selenium监听每一步操作

    1.创建类LogEventListener.java, 如下: package com.demo; import org.openqa.selenium.By; import org.openqa.s ...

  7. selenium从入门到应用 - 6,EventFiringWebDriver和监听器

    本系列所有代码 https://github.com/zhangting85/simpleWebtest 本文将介绍一个Java+TestNG+Maven+Selenium的web自动化测试脚本环境下 ...

  8. (六)爬虫之使用selenium

    selenium是使用javascript编写,主要用来进行web应用程序测试,在python爬虫中可以用来进行动态网页爬取,解决爬虫中的javascript渲染(执行js语句).总结记录下,以备后面 ...

  9. centos 无界面安装selenium+chrome+chromedirver的设置

    配了一中午的,好不容易正好记录下. 1.我的centos的位数 输入rpm -q centos-release 结果:centos-release-7-4.1708.el7.centos.x86_64 ...

  10. selenium python bindings 写测试用例

    这章总结selenium在UI测试方面的用法 import unittest from selenium import webdriver from selenium.webdriver.common ...

随机推荐

  1. Spiral Matrix(LintCode)

    Spiral Matrix Given a matrix of m x n elements (m rows, n columns), return all elements of the matri ...

  2. 如何使用Web字体?

    如何使用Web字体 嵌入Web字体的关键是@font-face规则,通过它可以指定浏览器下载web字体的地址,以及如何在样式表中引用该字体 @font-face { font-family: Voll ...

  3. 【GCD】AtCoder Grand Contest 018 A - Getting Difference

    从大到小排序,相邻两项作差,求gcd,如果K是gcd的倍数并且K<=max{a(i)},必然有解,否则无解. 可以自己手画画证明. #include<cstdio> #include ...

  4. 【成端更新线段树模板】POJ3468-A Simple Problem with Integers

    http://poj.org/problem?id=3468 _(:зゝ∠)_我又活着回来啦,前段时间太忙了写的题没时间扔上来,以后再说. [问题描述] 成段加某一个值,然后询问区间和. [思路] 讲 ...

  5. Problem F: 程序填充(函数、指针):去数组负数

    #include <stdio.h> void f(int *a,int *m) { int i,j; ;i < *m;i++) ) { ;j++) a[j]=a[j+]; (*m) ...

  6. JavaScript中的with语句

    执行环境的类型有两种:全局执行环境和局部执行环境(函数执行环境). 1.全局执行环境的变量对象是window对象,是JS代码开始运行时的默认环境.全局执行环境的变量对象始终都是作用域链中的最后一个对象 ...

  7. Linux下启动和停止Java应用程序的Shell脚本

    转自:http://blog.csdn.net/jadyer/article/details/7960802 资料参考来源自兔大侠,并略作修改:http://www.tudaxia.com/archi ...

  8. LaTeX 的对参考文献的处理

      LaTeX 的对参考文献的处理实在是非常的方便,我用过几次,有些体会,写出来供大家 参考.当然,自己的功力还不够深,有些地方问题一解决就罢手了,没有细究.     LaTeX 对参考文献的处理有这 ...

  9. [转]Loading and Running a Local Package Programmatically

    本文转自:http://msdn.microsoft.com/en-us/library/ms136090.aspx You can run Integration Services packages ...

  10. xss payload

    xss payload可以使用富客户端文本书写,大多数用javascript,少部分用actionscript等等. 1.盗取cookie,发起cookie劫持 使用xss漏洞插入cookie.js ...