Selenium的webdriver

引进的webdriver

Selenium 2.0中的主要新功能是WebDriver API的集成。开发Selenium-WebDriver是为了更好地支持动态网页,页面元素可能会改变,页面本身不会被重新加载。WebDriver的目标是提供一个设计良好的面向对象API,为现代高级Web应用程序测试问题提供更好的支持。

WebDriver如何“驱动”浏览器?

Selenium-WebDriver使用每个浏览器对自动化的原生支持直接调用浏览器。它使用内置的浏览器支持自动化,直接驱动浏览器。

WebDriver和Selenium- Server

如果浏览器和测试将全部在同一台机器上运行,并且测试只使用WebDriver API,那么不需要运行Selenium-Server; WebDriver将直接运行浏览器。

Selenium-WebDriver使用Selenium-Server有一些原因。

  • 正在使用Selenium-Grid将测试分布到多台机器或虚拟机(VM)上。
  • 要连接到具有特定浏览器版本的远程机器,该机器不在当前机器上。
  • 不使用Java绑定(即Python,C#或Ruby),并且想要使用HtmlUnit驱动程序

 设置Selenium-WebDriver项目

安装Selenium意味着在一个开发中设置一个项目,这样就可以使用Selenium编写一个程序。如何做到这一点取决于编程语言和开发环境。

Python的

如果正在使用Python进行自动测试,那么可能已经熟悉Python的开发了。要将Selenium添加到Python环境,从命令行运行以下命令。

 pip install selenium

通过示例介绍Selenium-WebDriver API

WebDriver是一个自动化Web应用程序测试的工具,特别是验证它们是否按预期工作。它的目的是提供一个友好的API,它易于探索和理解,它不受任何特定的测试框架的束缚,因此它可以在单元测试项目中使用,也可以从简单的老“main”方法中使用。

下载各个浏览器的WebDriver,将.exe文件直接放置于Python的主目录里。

 示例:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

# go to the google home page
driver.get("http://www.google.com")

# the page is ajaxy so the title is originally this:
print(driver.title)

# find the element that's name attribute is q (the google search box)
inputElement = driver.find_element_by_name("q")

# type in the search
inputElement.send_keys("cheese!")

# submit the form (although google automatically searches now without submitting)
inputElement.submit()

try:
    # we have to wait for the page to refresh, the last thing that seems to be updated is the title
    WebDriverWait(driver, 10).until(EC.title_contains("cheese!"))

    # You should see "cheese! - Google Search"
    print(driver.title)

finally:
    driver.quit()

 

原文地址:https://www.cnblogs.com/weiweim/p/8436181.html