selenium 测试小技巧
selenium 测试小技巧
设置下载文件的存储位置
对于有下载文件并且读取下载内容来确定测试结果的小伙伴来说,这很实用!
options = webdriver.ChromeOptions()
pref = {"download.default_directory": your_download_path}
options.add_experimental_option("prefs", pref)
获取当前case名称
当一个测试类中有N个测试case时,无法区分当前测试进行到哪个case有时会很难受!打印出来就好了!
print 'current testcase : {0}'.format(unittest.TestCase.id(self))
>>> current testcase : test1.your_test_class.your_test_case
can't find element 解决
寻找同一个元素两次,找到了继续执行,没有找到则寻找第二次,仍旧没找到则报错!
预防一个元素因为页面加载原因无法找到而导致的失败
使用ActionChains寻找元素,防止发生找到元素,但是无法点击该点的错误!
def action_click(self, name, value):
attempts = 0
while attempts < 2:
try:
self.driver.implicitly_wait(wait_time)
ele = self.driver.find_element(by=name, value=value)
ActionChains(self.driver).move_to_element(ele).click().perform()
time.sleep(sleep_time)
break
except Exception:
attempts += 1
if attempts == 2:
print 'can\'t find correct WebElement, please check it!'
点击动态生成的按钮
测试过程中,有时会碰到右键点击才会出现的菜单栏,因为是动态生成的,有些甚至不会有Html信息,不过不用着急,selenium自有办法对付:
action = ActionChains(self.driver.driver)
action.move_by_offset(500, 500).context_click().send_keys(Keys.ARROW_DOWN).send_keys(Keys.RETURN)
此类动态生成的菜单,多有使用按键操作的方法!此时只需要调用Keys类中的各种键盘按键就可以操作选中所需的按钮!最后RETURN实现操作!
选择文件
上传文件时,如果Html贴心的给你设置了上传路径的Input标签,那就可以很舒服的使用sendkeys,将路径键入之后就可以了!但是有时前端工程师并不那么的贴心(对,我说的就是谷歌的前端工程师),他会使用各种高端技巧来生成文件路径,其中有一种叫动态生成,他会调用win/ubuntu等系统的文件选择界面,选中后动态生成文件路径(懵逼脸)!这时就需要用到额外的包类:pywinauto。。此功能仅限win系统使用。
app = pywinauto.application.Application()
time.sleep(win_sleep_time)
main_window = app[u'Open']
ctrl = main_window[u'Edit']
main_window.SetFocus()
ctrl.Click()
time.sleep(win_sleep_time)
ctrl.TypeKeys(file_path)
time.sleep(win_sleep_time)
ctrl_bis = main_window[u'OpenButton'] # open file button
time.sleep(win_sleep_time)
具体而言,就是首先main_window = app[u'Open']定位到你Open界面,然后定位都输入栏,键入路径之后点击打开按钮完成选择文件操作,一般这种上传文件的方式打开按钮包含了上传功能。
人生苦短,用python能增加寿命吗?