Remote WebDriver

WebDriver实现。

class selenium.webdriver.remote.webdriver.WebDriver(command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=None, browser_profile=None, proxy=None, keep_alive=False, file_detector=None)

Bases: object 控制浏览器向remote server发送命令。Remote server 运行的协议定义为https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. 属性: * session_id- webdriver用于打开和控制浏览器窗口的ID字符串 * capabilities- Dictionaty of effective capabilities of this browser session as returned    remote server,见https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities * command_executor -远程链接。RemoteConnection对象执行命令。 * error_handler- errorhandler. ErrorHandler对象用于处理错误。     add_cookie(cookie_dict)

添加cookie到当前会话。 Args: * cookie_dict:字典对象,具有所需要的秘钥-”name"和“value". keys选项 ”path", "domain", "secure", "expiry"

用法:

driver.add_cookie({'name':'foo', 'value':'bar'}) driver.add_cookie({'name':'foo', 'value':
'bar', 'path':'/'}) driver.add_cookie({'name':'foo', 'value':'bar','path':'/','secure':True})

back()

浏览器历史记录中后退一步 用法:driver.back()

close()

关闭当前窗口 用法:driver.close()

create_web_element(element_id)

创建指定元素id的web元素

delete_all_cookies()

删除会话中所有的cookies 用法:driver.delete_all_cookies

delete_cookies(name)

删除给出名字的单一cookie 用法:driver.delete_cookie('my_cookie')

execute(driver_command, params=None)

通过 command.CommandExecutor发送命令 参数: * driver_command: 执行命令名称的字符串 * params: 使用命令发送的命名参数的字典 返回:命令的json导入到字典对象

excute_async_scipt(scipt, *args)

异步执行当前窗口/框架中的javascript Args: * script: 要执行的javascript * *ags: 任何javascript适用的参数 用法:driver.execute_async_script('document.title')

execute_script(script, *args)

同步执行当前窗口/框架中的javascript Args: * script: 要执行的javascript * *ags: 任何javascript适用的参数 用法:driver.execute_scipt('document.title')

file_detector_context(*args, **kwds)

在limited context覆盖当前的file detector. 确保original file detector已设置。 例如: with webdriver.file_detector_context(UselessFileDetector): someinput.send_keys('/etc/hosts')

参数: file_detector_clss- 如果类不同,需要提供文件检测器的类

从当前file_detector,那么该类用args和kwargs实例化,并在上下文管理器的持续时间期间用作文件检测器。

args- 期间需要传递给file detector的可选参数
kwargs - 关键字参数,传递方式和args相同

find_element(by='id', value=None)

'Private'方法由find_element_by_方法们使用 用法: 使用相应的find_element_by_ 替换 返回: WebElement

find_element_by_class_name(name)

按类名查找元素 参数: name-要查找元素的类名 用法: driver.find_element_by_class_name("foo")

find_element_by_css_selector(css_selector)

通过css selector查找元素 参数:css_selector 查找元素使用的css selector 用法:driver.find_element_by_css_selector('#foo')

find_element_by_id(id_)

通过id查找元素 参数: id 查找元素的id 用法: driver.find_element_by_id('foo')

find_element_by_link_text(link_text)

通过link text查找元素 参数: link_text 查找元素的link_text 用法: driver.find_element_by_link_text('Sign ln')

find_element_by_name(name)

通过name查找元素 参数: name: 查找元素的name 用法: driver.find_element_by_name('foo')

find_element_by_xpath(xpath)

通过xpath查找元素 args: xpath 查找元素的xpath定位器 用法:driver.find_element_by_xpath('//div/td/[1]')

find_element(by='id', value=None)

find_elements_by_methods使用的'Pvivate'方法 用法: 使用符合要求的find_elements_by_替换现有的 返回类型: WebElement列表

find_elements_by_class_name(name)

按类名查找元素 参数name: 查找元素的类名 用法:driver.find_elements_by_class_name('foo')

find_elements_by_css_selector(css_selector)

按css selector查找元素 css_selector: 查找元素使用的css selector 用法:driver.find_element_by_css_selector('.foo')

find_elements_by_id(id_)

按id查找多个元素 id_:要查找元素的id

find_elements_by_link_text(text)

通过链接文本查找元素 link_text: 查找元素的链接文本 driver.find_elements_by_link_text('Sign In')

find_elements_by_name(name)

按名称查找元素 name:查找元素的名称 driver.find_elements_by_name('foo')

find_elements_by_partial_link_text(link_text)

通过部分匹配链接文本查找元素。 link_text: 查找元素部分匹配的链接文本 driver.find_element_by_partial_link_text('Sign')

find_elements_by_tag_name(name)

通过tag name查找元素 name: 查找元素使用的tag name driver.find_elements_by_tag_name('foo')

find_elements_by_xpath(xpath)

通过xpath查找多个元素 xpath: 要查找元素的xpath的定位符 driver.find_elements_by_xpath("//div[contains(@class, 'foo')]")

forward()

回退一次浏览器历史记录 driver.forward()

get(url)

在当前浏览器窗口加载网页

get_cookie(name)

按名称找到单个cookie,如果找到,返回cookie,没有返回None driver.get_cookie('my_cookie')

get_cookies()

返回一组字典,对应当前会话可用的cookies

driver.get_cookies()

get_log(log_type)

获取给定log类型的log log_type:返回log的log类型 用法:driver.get_log('browser') driver.get_log('driver') driver.get_log('client') driver.get_log('server')

get_screenshot_as_base64()

获取当前窗口截屏的base64编码字符串 这个在嵌入图像到html时非常有用。 用法:driver.get_screentshot_as_base64()

get_screenshot_as_file(filename)

获取当前窗口的截屏。如果存在,返回False 任何IOError,否则返回True.在filename中使用绝对路径 filename: 将屏幕截图保存到的完整路径。 driver.get_screenshot_as_file('/Screenshots/foo.png')

get_screenshot_as_png()

获取当前窗口的截屏,并保存为二进制数据。 driver.get_screenshot_as_png()

get_window_position(windowHandle='current')

获取当前窗口的x,y位置 driver.get_window_position()

get_window_size(windowHandle='current')

获取当前窗口的宽和高 driver.get_window_size()

implicitly_wait(time_to_wait)

设置固定超时时间等待元素被找到,或命令完成 这个方法只需要在每个对话框执行一次。设置timeout需要调用execute_async_script. time_to_wait:等待的时间 driver.implicitly_wait(30)

maximize_window()

将当前webdriver的窗口最大化

quit()

退出dirver并关闭每一个关联的窗口 driver.quit()

refresh()

刷新当前的窗口 driver.refresh()

save_screenshot(filename)

同 get_screenshot_as_file.

set_page_load_timeout(time_to_wait)

设置等待网页加载完成的时间(抛出异常之前) time_to_wait:等待的时间 driver.set_page_load_timeout(30)

set_script_timeout(time_to_wait)

设置脚本运行的时间,直到抛出异常之前 time_to_wait:等待时间 driver.set_script_timeout(30)

set_window_position(x,y, windowHandle='current')

设置当前窗口的x,y driver.set_window_position(0,0)     set_window_size( width, height, windowHandle='current')

设置当前窗口的高和宽 driver.set_window_size(800,600)

start_client()

启动新窗口前调用。这个方法使用时可以重写。

start_session(desired_capabilities, browser_profile=None)

创建所需功能的新会话 browser_name : 浏览器请求的名称 vesion: 哪些浏览器版本要求。 platform: 哪个平台要求在浏览器上。 javascript_enabled :新回话是否应支持JavaScript。 browser_profile : 一个selenium.webdriver.firefox.firefox_profile.FirefoxProfile对象。只有当被请求的Firefox使用。

stop_client()

执行quit命令后调用。用户可以根据需要自定义shutdown行为方法

switch_to_active_element()

Deprecated use driver.switch_to.active_element

switch_to_alert()

Deprecated use driver.switch_to.alert

switch_to_default_content()

Deprecated use driver.switch_to.default_content

switch_to_frame(frame_reference)

Deprecated use driver.switch_to.frame

switch_to_window(window_name)

Deprecated use driver.switch_to.window

application_cache

返回一个与浏览器的应用程序缓存交互的ApplicationCache对象

current_url

获取当前页的URL driver.current_url

current_window_handle

返回当前窗口的handle driver.current_window_handle

desired_capabilities

返回正在使用当前所需功能的驱动程序     file_detector

log_types

获取可用log types的列表 driver.log_types

mobile

name 返回此实例中底层浏览器的名称 driver.name

orientation 获取当前设备的当前位置 orientation = driver.orientation

page_source 获取当前页面的源码 driver.page_source

switch_to

title 返回当前页面的title driver.title

window_handles 返回当前会话中所有窗口的句柄 driver.window_handles

WebElement

class selenium.webdriver.remote.webelement.WebElement(parent, id_, w3c=False)

Bases:object
表示一个DOM元素
通常与一个文档交互的所有有趣操作将通过该接口来执行
所有方法调用前会做一个freshness check,确保引用元素仍然有效。这实际上是检查元素是否仍然连接到DOM.如果检测测试失败,将会抛出StaleElementReferenceException异常,并且所有调用都会失败。

clear()

    清除文本,如果是一个文本输入元素。

click()

    点击元素

find_element(by='id',value=None)

find_element_by_class_name(name)

    通过子元素的类名查找元素
    name:查找元素的类名

find_element_by_css_selector(css_selector)

    通过子元素的CSS selector查找元素
    css_selector: CSS selector string 例如‘a.nav#home'

find_element_by_id(id_)

    通过子元素的ID查找元素
    id_: 用于定位的子元素的ID

find_elements_by_partial_link_text(link_text)
    通过子元素的link text查找元素的列表
    link_text:元素的Link text

find_element_by_tag_name(name)
    通过子元素的tag name查找元素的列表
    name - html的tag的name(如h1,a,span)

find_elements_by_xpath(xpath)

    通过xpath查找元素
    xpath:xpath位置字符
    基本路径相对于这个元素的位置
    这将选择此元素下的所有链接。
        myelement.find_elements_by_xpath(".//a")

    然而,将会选择该页面本身的所有links
        myelement.find_elements_by_xpath("//a")

    get_attribute(name)

        获取给定元素的属性或特性
        这个方法会首先尝试返回给定名字的属性的值。如果具有该名称的属性不存在,它返回具有相同名称的属性值。如果什么都没有,返回None
        name:检索的属性的名字
        例如:
            #check if the "active" CSS class is applied to an element.
            is_active = "active" in target_element.get_attribute("class")

    is_displayed()
         判断该元素是否对用户可见。      

    is_enabled()
         返回元素是否已启用

    is_selected()
        返回元素是否已选择
        可以用来检查复选框或单选框是否已选择

    Screenshot(filename)

        获取当前元素的截屏。如果出现任何IOError,返回False,否则返回True。filename使用绝对路径。
        filename: 保存截屏文件的绝对路径
        用法:element.Screenshot('/Screenshots/foo.png')

    send_keys(*value)
        模拟键入元素
        value: 键入字符串,或设置表单。设置文件输出,可以为文件的绝对路径

        可以用来发送简单的按键事件或填充表单:
           form_textfield = driver.find_element_by_name('username')
           form_textfield.send_keys("admin")

        同样可以用于设置文件输入。

            file_input = driver.find_element_by_name('profilePic')
            file_input.send_keys("path/to/profilepic.gif")
            #Generally it's better to wrap the file path in one of the methods
            #in os.path to return the actual path to support cross OS testing.
            # file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))

    submit()
        提交表单

    value_of_css_property(property_name)
         CSS属性的值

    id
        selenium 使用的内部编号
        主要内部用户使用。可以用于简单检查2个元素是否为同一元素,可以使用“==”:
            if element1 == element2:
                print("These 2 are equal")

    location
        在渲染画布中元素的位置

    location_once_scrolled_into_view
        元素可能在没有提示的情况下修改。用它可以找到我们可以点击的元素。此方法可以将元素滚动到视图。
        返回屏幕上的顶部左侧角落的位置,或者None如果该元素是不可见的。

    parent
      Internal reference to the WebDriver instance this element was found from.

    rect
       元素的位置和大小的字典

    screenshot_as_base64
        获取当前元素截屏的base64位编码
        用法:img_b64 = element.screenshot_as_base64

    screensh_as_png
        获取当前元素截屏的二进制
        用法:element_png = element.screensh_as_png

    size 
        元素的大小

    tag_name 
        元素的tagname属性

    text
        元素的文本

UI Support

class selenium.webdriver.support.select.Select(webelement) deselect_all() 清除所有选中的条目。只对选中多个支持的选择有效。如果SELECT如果不支持复合选择,则抛出NotImplementedError.

deselect_by_index(index)
    取消给定索引出的选项。通过元素的“index”属性进行,不仅仅通过计数。
    index: 被取消选项的索引
    如果指定的index没有SELECT,将抛出“NoSuchElementException"异常。

deselect_by_value(value)
   取消匹配参数值的选项。例如给点参数”foo",将取消这样的选项:
       <option value="foo">Bar</option>

   value: 要匹配的值
   如果没有选项匹配给定的参数值,将抛出“NoSuchElementException"异常。

deselect_by_visible_text(text)
       取消同参数值匹配的可见文本的选择项。例如给出”Bar",这样的选项就会取消:
           <option value="foo">Bar</option>

           text:要匹配的可见文本

select_by_index(index)
    选择指定索引的选项。通过元素的index属性进行,不是通过counting.
    index:被选中选项的索引
    如果给定的索引指定的选项不存在,将抛出”NoSuchElementException"异常

select_by_value(value)
    选择匹配参数值的所有选项。例如,给定“foo",这样的选项将会选中:
        <option value="foo">Bar</option>
        vale:需要匹配的值
    如果没有选项匹配给定的参数值,将抛出”NoSuchElementException"异常。

select_by_visible_text(text)
    选择所有匹配可视文本的选项。例如给定参数“Bar",这样的选项将会选中:
        <option value="foo">Bar</option>
        text:要匹配的可见文本
    如果没有选项匹配给定的参数值,将会抛出StaleElementReferenceException异常。

all_selected_options
   返回属于这个选项标签的所有选择选项的列表

first_selected_option
   返回选项标签的第一个选项(或则当前已选中的选项)

options 
返回属于这个选择标签的所有选项的列表

class selenium.webdriver.support.wait.WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None) Bases:object

until(method, message=")
    Calls the method provided with the driver as an argument until the return value is not False.

until_not(method, message='')

    Calls the method provided with the driver as an argument until the return value is False.

Color Support

class selenium.webdriver.support.color.Color(red, green, blue, alpha=1) Bases:object 颜色转换支持类。 例如: from selenium.webdriver.support.color import Color

    print(Color.from_string('#00ff33').rgba)
    print(Color.from_string('rgb(1, 255, 3)').hex)
    print(Color.from_string('blue').rgba)

    static from_string(str_)

    hex
    rgb
    rgba

Expected conditions Support

class selenium.webdriver.support.expected_conditions.alert_is_present Bases:object 弹出预期alert

class selenium.webdriver.support.expected_conditions.element_located_selection_state_to_be(locator, is_selected)

Bases:object
An expectation to locate an element and check if the selection state specified is in that state. locator is a tuple of (by, path) is_selected is a boolean

class selenium.webdriver.support.expected_conditions.element_located_to_be_selected(locator)

Bases: object

An expectation for the element to be located is selected. locator is a tuple of (by, path)

class selenium.webdriver.support.expected_conditions.element_selection_state_to_be(element, is_selected)

Bases: object

An expectation for checking if the given element is selected. element is WebElement object is_selected is a Boolean.

class selenium.webdriver.support.expected_conditions.element_to_be_clickable(locator)

Bases: object

An Expectation for checking an element is visible and enabled such that you can click it.

class selenium.webdriver.support.expected_conditions.element_to_be_selected(element)

Bases: object

An expectation for checking the selection is selected. element is WebElement object

class selenium.webdriver.support.expected_conditions.frame_to_be_available_and_switch_to_it(locator)

Bases: object

An expectation for checking whether the given frame is available to switch to. If the frame is available it switches the given driver to the specified frame.

class selenium.webdriver.support.expected_conditions.invisibility_of_element_located(locator)

Bases: object

An Expectation for checking that an element is either invisible or not present on the DOM.

locator used to find the element

class selenium.webdriver.support.expected_conditions.presence_of_all_elements_located(locator)

Bases: object

An expectation for checking that there is at least one element present on a web page. locator is used to find the element returns the list of WebElements once they are located

class selenium.webdriver.support.expected_conditions.presence_of_element_located(locator)

Bases: object

An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible. locator - used to find the element returns the WebElement once it is located

class selenium.webdriver.support.expected_conditions.staleness_of(element)

Bases: object

Wait until an element is no longer attached to the DOM. element is the element to wait for. returns False if the element is still attached to the DOM, true otherwise.

class selenium.webdriver.support.expected_conditions.text_to_be_present_in_element(locator, text_)

Bases: object

An expectation for checking if the given text is present in the specified element. locator, text

class selenium.webdriver.support.expected_conditions.text_to_be_present_in_element_value(locator, text_)

Bases: object

An expectation for checking if the given text is present in the elements locator, text

class selenium.webdriver.support.expected_conditions.title_contains(title)

Bases: object

An expectation for checking that the title contains a case-sensitive substring. title is the fragment of title expected returns True when the title matches, False otherwise

class selenium.webdriver.support.expected_conditions.title_is(title)

Bases: object

An expectation for checking the title of a page. title is the expected title, which must be an exact match returns True if the title matches, false otherwise.

class selenium.webdriver.support.expected_conditions.visibility_of(element)

Bases: object

An expectation for checking that an element, known to be present on the DOM of a page, is visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. element is the WebElement returns the (same) WebElement once it is visible

class selenium.webdriver.support.expected_conditions.visibility_of_any_elements_located(locator)

Bases: object

An expectation for checking that there is at least one element visible on a web page. locator is used to find the element returns the list of WebElements once they are located

class selenium.webdriver.support.expected_conditions.visibility_of_element_located(locator)

Bases: object

An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. locator - used to find the element returns the WebElement once it is located and visible

Top^

上一篇Selenium主题8 下一篇Selenium主题10

by 李鹏