1、什么是toast?
toast属于一种轻量级的反馈,常常以小弹框的形式出现,一般出现1到3秒会自动消失,可以出现在屏幕上中下任意位置,首先来看下web页面上的toast是什么样子的。
2、定位toast
这种toast,往往就存在3秒中左右,3秒中,打开浏览器这些内容都没了,怎么定位呢?安静给大家介绍一个小技巧。打开chrome进入F12页面进入到Sources
等出现toast弹框信息后,点击暂停按钮
然后切到elements选项,就可以定位toast
3、代码封装
from selenium.webdriver.support import expected_conditions
def base_get_toast_text(self, loc):
# 获取toast的文本信息
toast_text = WebDriverWait(self.driver, 10, 0.5).until(expected_conditions.presence_of_element_located(loc))
return toast_text.text
或者添加捕获异常
# 注意别导入错了!!!
from selenium.webdriver.support import expected_conditions as EC
def get_toast_text(driver, timeout=15, poll_frequency=0.1):
'''
func:定位Toast元素,获取text属性值
:param driver: driver实例对象
:param timeout: 元素定位超时时间
:param poll_frequency: 查询频率
:return: toast文本内容
'''
toast_loc = (By.XPATH, '//*[@class="android.widget.Toast"]')
try:
toast = WebDriverWait(driver, timeout, poll_frequency).until(
EC.presence_of_element_located(toast_loc)
)
# toast_text = toast.get_attribute('text')
toast_text = toast.text
return toast_text
except Exception as e:
print(e)
4、调用
# 订单提交成功的Toast信息
loc = (By.CSS_SELECTOR, 'div[class="layui-layer-content layui-layer-padding"]')
toast = base_get_toast_text(loc)
print(toast)