Selenium3 Python WebDriver API源码探析(4):Web元素的属性和方法

Selenium中网页中DOM元素的实现为selenium\webdriver\remote\webelement.py中的WebElement类。
WebDriver API中定位元素的方法在《Selenium3 Python WebDriver API源码探析(3):定位元素》已经简单介绍。本文主要介绍网页元素的属性和方法。

属性或特性

元素的标签名称

作用:获得当前元素的标签名称
签名:el.tag_name
值类型:字符串,例如'input'

元素的文本

作用:获得当前元素的文本内容
签名:el.text
值类型:字符串,例如'百度热榜'

获取元素大小

作用:获取元素的大小(以像素为单位)。
签名: el.size
值类型:字典,例如:{'height': 14.0, 'width': 0.0}

获取元素位置

作用:获取元素的位置(以像素为单位)。
签名: el.location
值类型:字典,例如:{'x': 371, 'y': 286}

获取元素矩形区域

作用:获取元素的矩形区域(元素位置和大小)。
签名: el.rect
值类型:字典,例如:{'x': 371.0, 'y': 286, 'width': 0.0, 'height': 14.0}

元素的内部id

作用:获得当前元素在selenium中的内部id(主要用于判断两个元素是否相同)
签名:el.id
值类型:字符串

元素的引用的WebDriver实例

作用:获得当前元素引用的WebDriver实例
签名:el.parent
值类型:WebDriver实例

@property
def location_once_scrolled_into_view(self):
    """THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover
    where on the screen an element is so that we can click it. This method
    should cause the element to be scrolled into view.

    Returns the top lefthand corner location on the screen, or ``None`` if
    the element is not visible.

    """
    if self._w3c:
        old_loc = self._execute(Command.W3C_EXECUTE_SCRIPT, {
    
    
            'script': "arguments[0].scrollIntoView(true); return arguments[0].getBoundingClientRect()",
            'args': [self]})['value']
        return {
    
    "x": round(old_loc['x']),
                "y": round(old_loc['y'])}
    else:
        return self._execute(Command.GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW)['value']

元素属性或CSS属性的获取方法

获取元素属性

作用:获得当前元素的属性特性(property)或(attribute),优先查找特性,如果没有,再查找同名属性,如果都找不到返回None
签名:el.get_attribute(name)
返回值:布尔值、字符串、None
源码:

def get_attribute(self, name):
    """Gets the given attribute or property of the element.

    This method will first try to return the value of a property with the
    given name. If a property with that name doesn't exist, it returns the
    value of the attribute with the same name. If there's no attribute with
    that name, ``None`` is returned.

    Values which are considered truthy, that is equals "true" or "false",
    are returned as booleans.  All other non-``None`` values are returned
    as strings.  For attributes or properties which do not exist, ``None``
    is returned.

    :Args:
        - name - Name of the attribute/property to retrieve.

    Example::

        # Check if the "active" CSS class is applied to an element.
        is_active = "active" in target_element.get_attribute("class")

    """

    attributeValue = ''
    if self._w3c:
        attributeValue = self.parent.execute_script(
            "return (%s).apply(null, arguments);" % getAttribute_js,
            self, name)
    else:
        resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {
    
    'name': name})
        attributeValue = resp.get('value')
        if attributeValue is not None:
            if name != 'value' and attributeValue.lower() in ('true', 'false'):
                attributeValue = attributeValue.lower()
    return attributeValue

获取元素CSS属性

作用:获得当前元素的CSS属性值。
签名:el.value_of_css_property(property_name)
返回值:字符串

状态检测类方法

元素是否处于选择状态

作用:检测元素是否处于选择状态。
签名:el.is_selected()
返回值:布尔值

元素是否可用

作用:检测元素是否可用。
签名:el.is_enabled()
返回值:布尔值

元素是否可见

作用:检测元素是否对可见。
签名:el.is_displayed()
返回值:布尔值

动作类方法

点击元素

作用:点击元素。
签名:el.click()

向表单元素内输入内容

作用:向表单元素内输入内容。
签名:el.send_keys(value)

清空表单元素内容

作用:清空表单元素内容。
签名:el.clear()

提交表单

作用:提交表单。
签名:el.submit()

案例1:演示元素的属性和方法

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.baidu.com")
hot = driver.find_element_by_class_name('hot-title')
print(repr(hot.tag_name), type(hot.tag_name))
print(repr(hot.text), type(hot.text))
print(repr(hot.size), type(hot.size))
print(repr(hot.location), type(hot.location))
print(repr(hot.rect), type(hot.rect))
print(repr(hot.id), type(hot.id))
print(repr(hot.parent), type(hot.parent))
print(repr(hot.get_attribute('text')), type(hot.get_attribute('text')))
print(repr(hot.value_of_css_property('color')), type(hot.value_of_css_property('color')))
print(repr(hot.is_selected()), type(hot.is_selected()))
print(repr(hot.is_enabled()), type(hot.is_enabled()))
print(repr(hot.is_displayed()), type(hot.is_displayed()))
driver.quit()

输出:

'a' <class 'str'>
'百度热榜' <class 'str'>
{
    
    'height': 14.0, 'width': 0.0} <class 'dict'>
{
    
    'x': 371, 'y': 286} <class 'dict'>
{
    
    'x': 371.0, 'y': 286.066650390625, 'width': 0.0, 'height': 14.0} <class 'dict'>
'b599675f-2d0b-4a7e-aa5f-f7e91320ceff' <class 'str'>
<selenium.webdriver.firefox.webdriver.WebDriver (session="37e5167a-b85c-4c94-b139-c040b4a00abd")> <class 'selenium.webdriver.firefox.webdriver.WebDriver'>
'百度热榜' <class 'str'>
'rgb(0, 0, 238)' <class 'str'>
False <class 'bool'>
True <class 'bool'>
True <class 'bool'>

案例2:演示元素的动作方法

from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.get("http://www.baidu.com")
# 获取搜索文本框元素
input = driver.find_element_by_id('kw')
# 获取搜索按钮
submit = driver.find_element_by_id('su')
# 向文本框输入test
input.send_keys('test')
time.sleep(5)
# 清除文本框内容
input.clear()
time.sleep(5)
# 向文本框输入test1
input.send_keys('test1')
# 提交表单
input.submit()

猜你喜欢

转载自blog.csdn.net/mighty13/article/details/114679716