Selenium2+python自动化63-二次封装(click/send_kesy),selenium263-,我们学了显示等待后,
Selenium2+python自动化63-二次封装(click/send_kesy),selenium263-,我们学了显示等待后,
我们学了显示等待后,就不需要sleep了,然后查找元素方法用参数化去定位,这样定位方法更灵活了,但是这样写起来代码会很长了,于是问题来了,总不能每次定位一个元素都要写一大堆代码吧?这时候就要学会封装啦
一、显示等待
1.如果你的定位元素代码,还是这样:driver.find_element_by_id("kw").send_keys("yoyo"),那说明你还停留在小学水平,如何让代码提升逼格呢?
2.前面讲过显示等待相对于sleep来说更省时间,定位元素更靠谱,不会出现一会正常运行,一会又报错的情况,所以我们的定位需与WebDriverWait结合
3.以百度的搜索为例
二、封装定位方法
1.从上面代码看太长了,每次定位写一大串,这样不方便阅读,写代码的效率也低,于是我们可以把定位方法进行封装
2.定位方法封装后,我们每次调用自己写的方法就方便多了
三、封装成类
1.我们可以把send_keys()和click()方法也一起封装,写到一个类里
2.定位那里很多小伙伴弄不清楚lambda这个函数,其实不一定要用这个,我们可以用EC模块的presence_of_element_located()这个方法,参数直接传locator就可以了
3.以下是presence_of_element_located这个方法的源码:
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)
四、参考代码
1.把get、find_element、click、send_keys封装成类# coding:utf-8from selenium import webdriverfrom selenium.common.exceptions import * # 导入所有的异常类from selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.ui import WebDriverWaitclass Yoyo(object): """基于原生的selenium框架做了二次封装.""" def __init__(self): """启动浏览器参数化,默认启动firefox.""" self.driver = webdriver.Firefox() def get(self, url): ‘‘‘使用get打开url‘‘‘ self.driver.get(url) def find_element(self, locator, timeout=10): ‘‘‘定位元素方法封装‘‘‘ element = WebDriverWait(self.driver, timeout, 1).until(EC.presence_of_element_located(locator)) return element def click(self, locator): ‘‘‘点击操作‘‘‘ element = self.find_element(locator) element.click() def send_keys(self, locator, text): ‘‘‘发送文本,清空后输入‘‘‘ element = self.find_element(locator) element.clear() element.send_keys(text)if __name__ == "__main__": d = Yoyo() # 启动firefox d.get("https://www.baidu.com") input_loc = ("id", "kw") d.send_keys(input_loc, "yoyo") # 输入搜索内容 button_loc = ("id", "kw") d.click(button_loc) # 点击搜索按钮
Selenium2+python自动化63-二次封装(click/send_kesy)
相关内容
- 全栈Python 必备库,python必备库,强大的库:转自:微信
- 【概率论与数理统计】小结3 - 一维离散型随机变量及其
- selenium3+python自动化50-环境搭建(firefox),selenium350-,前
- 我整理的Python代码规则,整理python代码,首先,python有
- Selenium2+python自动化57-捕获异常(NoSuchElementException),
- python接口自动化23-token参数关联登录(登录拉勾网),
- 第三百五十四节,Python分布式爬虫打造搜索引擎Scrapy精
- 【Python 数据分析】module ‘numpy‘ has no attribute ‘array‘
- 关于基于python27使用 from pylab import * 报错问题,python2
- Pycharm+Python+PyQt5使用,pycharmpyqt5,转载自http://
评论关闭