分享

Selenium:元素判断_selenium判断元素是否存在

 福兮007 2023-08-29 发布于上海

判断元素是否存在

1、前面有介绍过使用Python中的sleep()方法来进行等待:等待一定的时间,让元素加载出来后再执行代码
⑴但是元素加载出来的时间是不固定的,有时长有时短,因此我们等待的时间就不固定了
⑵最好的办法是:每隔一定的时间后使用Selenium中的一些方法来判断元素是否加载了出来(这个就是后面要介绍的"显式等待")
①元素加载出来了,就不继续等待了
②元素未加载出来,就继续等待

2、另外就是在做自动化的时候,有时候会需要判断元素是否存在,iframe是否存在,以及一些弹出框是否存在,以便确定我们的操作是否符合预期
⑴相当于一种断言方式了

3、selenium提供了一个专门用于元素判断的模块:expected_conditions
⑴这个模块用的比较多的场景就是和显示等待一起使用,通过显示等待的方法来循环判断是否元素是否出现
⑵至于显示等待就后面介绍,这里单独介绍元素判断方法

常用方法介绍

1、expected_conditions的方法种类有很多。大部分都是判断元素的,但是也有判断其他的

方法名

描述

title_is

判断当前页面的title是否完全等于(==)预期字符串,返回布尔值

title_contains

判断当前页面的title是否包含预期字符串,返回布尔值

url_contains

判断当前页面的url是否精确等于预期,返回布尔值

presence_of_element_located

判断某个元素是否被加到了dom树里(元素是否加载出来),并不代表该元素一定可见,返回元素对象

visibility_of_element_located

判断某个元素是否可见. 可见代表元素非隐藏,并且元素的宽和高都不等于0,返回元素对象

visibility_of

跟上面的方法一样,只是上一个方法的参数为定位方法,该方法的参数为定位后的元素(element对象),返回元素对象

presence_of_all_elements_located

判断是否至少有1个元素存在于dom树中。举个例子,如果页面上有n个元素的class都是’column-md-3’,那么只要有1个元素存在,返回True

text_to_be_present_in_element

判断某个元素中的text是否包含预期的字符串,返回布尔值

text_to_be_present_in_element_value

判断某个元素中的value属性是否包含预期的字符串

frame_to_be_available_and_switch_to_it

判断该frame是否可以switch进去,如果可以且switch进去的话,返回True,否则返回False

invisibility_of_element_located

判断某个元素中是否不存在于dom树或不可见

element_to_be_clickable

判断某个元素中是否可见并且是可以点击,如果是的就返回这个元素,否则返回False

staleness_of

等某个元素从dom树中移除

element_to_be_selected

判断某个元素是否被选中了,一般用在下拉列表

element_selection_state_to_be

判断某个元素的选中状态是否符合预期

element_located_selection_state_to_be

跟上面的方法作用一样,只是上面的方法传入定位到的element,而这个方法传入定位方法

alert_is_present

判断页面上是否存在alert

new_window_is_opened

判断窗口是否增加,传入窗口数量

number_of_windows_to_be

期望窗口为多少

frame_to_be_available_and_switch_to_it

判断是否切换到iframe

注:
1、上面这些方法都会返回一个<class 'selenium.webdriver.support.expected_conditions.*’>对象,这个对象本质是一个方法函数(object)
不管最后元素是否是预期状态或找没找到元素等,都会先返回这个对象

2、因为这个对象的本质是一个方法函数,因此可通过**“返回的对象(浏览器对象)”**来获取具体的值(调用函数)
⑴找到元素:返回具体的element、True、False
⑵未找到元素:触发异常

title_is

1、作用:判断当前页面的title是否完全等于(==)预期字符串

2、源码:

class title_is(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."""
? ? def __init__(self, title):
? ? ? ? self.title = title

? ? def __call__(self, driver):
? ? ? ? return self.title == driver.title
"""
1、注释翻译:检查页面的title与期望值是都完全一致,如果完全一致,返回True,否则返回Flase
2、title_is()这个是一个class类型,里面有两个方法
3、__init__是初始化内容,参数是title,必填项
4、__call__是把实例变成一个对象,参数是driver,返回的是self.title == driver.title
"""

例1:

import time
from selenium import webdriver
# 导入所需模块
from selenium.webdriver.support import expected_conditions as EC

# 获取浏览器对象
driver = webdriver.Chrome()
# 设置浏览器窗口大小
driver.maximize_window()
# 进入页面
driver.get('https://www.baidu.com/')
#判断首页title是否为"百度一下,你就知道"
result = EC.title_is("百度一下,你就知道")
# title_is()方法直接返回的是一个对象,可通过浏览器对象继续获取具体的值
print(result) ?#可以看到这个对象本质是一个方法
print(type(result))
# 这里相当于是在调用函数:将浏览器对象作为参数传入title_is()方法返回值中获取具体的值
print(result(driver))

"""
<selenium.webdriver.support.expected_conditions.title_is object at 0x000002300CB626A0>
<class 'selenium.webdriver.support.expected_conditions.title_is'>
True
"""

presence_of_element_located

1、作用:判断某个元素是否被加到了dom树里,并不代表该元素一定可见,返回元素对象
⑴是否能在HTML文档中找到该元素

2、返回值:不管元素是否被加到了dom树里,该方法都会返回一个对象(本质是一个方法函数)
⑴若该元素加到了dom树里,可通过返回的对象来获取具体的元素WebElement对象(调用函数)
⑵若该元素未加到dom树里,通过返回的对象获取WebElement对象时报错

3、源码:

class presence_of_element_located(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
? ? """
? ? def __init__(self, locator):
? ? ? ? self.locator = locator

? ? def __call__(self, driver):
? ? ? ? return _find_element(driver, self.locator)

"""
参数locator:初始化内容,表示待检查元素的定位方式
其他方法若参数是locator,则表示必须传入元素的定位方式,而不是element对象
"""

**例2:**找到元素时

import time
from selenium import webdriver
# 导入所需模块
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

# 获取浏览器对象
driver = webdriver.Chrome()
# 设置浏览器窗口大小
driver.maximize_window()
# 进入页面
driver.get('https://www.baidu.com/')
#判断输入框是否可见
result = EC.presence_of_element_located((By.ID,"kw")) # 注意这里的写法(两个括号)
# 返回的是一个对象(本质是一个方法函数),需要通过浏览器对象继续获取具体的值
print(result)
print(type(result))
# 调用函数:将浏览器对象作为参数传入presence_of_element_located()方法返回值中获取具体的值WebElement对象
print(result(driver))

"""
<selenium.webdriver.support.expected_conditions.presence_of_element_located object at 0x000001F366428240>
<class 'selenium.webdriver.support.expected_conditions.presence_of_element_located'>
<selenium.webdriver.remote.webelement.WebElement (session="5c3459ca6d724c2fcaa172f63aaabde0", element="aad85da9-1b3a-476e-8f75-d2ac523696f3")>
"""

**例2_1:**未找到元素时

import time
from selenium import webdriver
# 导入所需模块
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

# 获取浏览器对象
driver = webdriver.Chrome()
# 设置浏览器窗口大小
driver.maximize_window()
# 进入页面
driver.get('https://www.baidu.com/')
#判断输入框是否可见
result = EC.presence_of_element_located((By.ID,"kw1")) # 注意这里的写法(两个括号)
print(result)
print(type(result))
# 未找到元素时presence_of_element_located依旧会返回一个对象,但是在获取元素对象时会报错
print(result(driver))

"""
<selenium.webdriver.support.expected_conditions.presence_of_element_located object at 0x0000019D3D638240>
<class 'selenium.webdriver.support.expected_conditions.presence_of_element_located'>

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="kw1"]"}
"""

visibility_of_element_located

1、作用:判断某个元素是否可见. 可见代表元素非隐藏,并且元素的宽和高都不等于0

2、源码:

class visibility_of_element_located(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
? ? """
? ? def __init__(self, locator):
? ? ? ? self.locator = locator

? ? def __call__(self, driver):
? ? ? ? try:
? ? ? ? ? ? return _element_if_visible(_find_element(driver, self.locator))
? ? ? ? except StaleElementReferenceException:
? ? ? ? ? ? return False

"""
参数locator:初始化内容,表示待检查元素的定位方式
其他方法若参数是locator,则表示必须传入元素的定位方式,而不是element对象
"""

例3:

import time
from selenium import webdriver
# 导入所需模块
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

# 获取浏览器对象
driver = webdriver.Chrome()
# 设置浏览器窗口大小
driver.maximize_window()
# 进入页面
driver.get('https://www.baidu.com/')
#判断输入框是否可见
result = EC.visibility_of_element_located((By.ID,"kw")) # 注意这里的写法(两个括号)
print(result)
print(type(result))

"""
返回的是一个对象
<selenium.webdriver.support.expected_conditions.visibility_of_element_located object at 0x000001B1713515C0>
<class 'selenium.webdriver.support.expected_conditions.visibility_of_element_located'>
"""

visibility_of

1、作用:跟上面的方法一样,只是上一个方法的参数为定位方法,该方法的参数为定位后的元素(element对象)

2、源码:

class visibility_of(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
? ? """
? ? def __init__(self, element):
? ? ? ? self.element = element

? ? def __call__(self, ignored):
? ? ? ? return _element_if_visible(self.element)

"""
参数element:初始化内容,表示待检查元素的element对象
其他方法若参数是element,则表示必须传入元素的element对象
"""

例4:

import time
from selenium import webdriver
# 导入所需模块
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

# 获取浏览器对象
driver = webdriver.Chrome()
# 设置浏览器窗口大小
driver.maximize_window()
# 进入页面
driver.get('https://www.baidu.com/')
#判断输入框是否可见
element = driver.find_element_by_id("kw")
result = EC.visibility_of(element)
print(result)
print(type(result))

"""
<selenium.webdriver.support.expected_conditions.visibility_of object at 0x000001F923994D30>
<class 'selenium.webdriver.support.expected_conditions.visibility_of'>

"""

text_to_be_present_in_element

1、作用:判断某个元素中的text是否包含预期的字符串

2、txt:表示标签对之间的数据

例5:

import time
from selenium import webdriver
# 导入所需模块
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

# 获取浏览器对象
driver = webdriver.Chrome()
# 设置浏览器窗口大小
driver.maximize_window()
# 进入页面
driver.get('https://www.baidu.com/')
#判断输入框是否可见
result = EC.text_to_be_present_in_element((By.ID,"s-top-loginbtn"),"登录") # 注意这里的写法(两个括号)
print(result)
print(type(result))
print(result(driver))
"""
<selenium.webdriver.support.expected_conditions.text_to_be_present_in_element object at 0x000001D397A93668>
<class 'selenium.webdriver.support.expected_conditions.text_to_be_present_in_element'>
True
"""

text_to_be_present_in_element_value

1、作用:判断某个元素中的value属性是否包含预期的字符串

2、该方法用于判断标签value属性的值(只针对于value属性)

例5:

import time
from selenium import webdriver
# 导入所需模块
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

# 获取浏览器对象
driver = webdriver.Chrome()
# 设置浏览器窗口大小
driver.maximize_window()
# 进入页面
driver.get('https://www.baidu.com/')
#判断输入框是否可见
# result = EC.text_to_be_present_in_element_value((By.ID,"su"),"百度一下") # 注意这里的写法(两个括号)
# print(result)
# print(type(result))
# print(result(driver))
# 或
result = EC.text_to_be_present_in_element_value((By.ID,"su"),"百度一下")(driver)
print(result)

"""
<selenium.webdriver.support.expected_conditions.text_to_be_present_in_element_value object at 0x000001D1AE911630>
<class 'selenium.webdriver.support.expected_conditions.text_to_be_present_in_element_value'>
True
"""

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多