python的selenium模块还不够健壮稳定(大多见于鼠标事件)的解决方法
当selenium将鼠标移动到注册了onmouse事件的元素上的时候,偶尔不能从弹出的层上获取到指定的元素,如下面这段代码:
..........
def pop_info(self):
driver = self.driver
user_meg = driver.find_element_by_xpath("//div[@class='basicInfo']/dl/dd[1]")
chains = ActionChains(driver)
chains.move_to_element(user_meg).perform()
.............
def find_username():
self.pop_info()
username = driver.find_element_by_xpath("//div[@class='user_meg_con']/p[@class='userBrief']/i/a[1]").text
return username
我们期望能用find_username方法获得用户名,但这个方法,有时不能成功。
为了解决这个问题,让find_username方法多次执行,直到成功,我们先设计一个工具方法,functions.loop_until_notblank
def loop_until_notblank(fun, times = 10): ''' 循环调用fun指定的次数(times),直到返回的结果不是空串 ''' for i in range(0, times): result = fun() if result != '': return result return ''
使用示例如下:
.............
def find_username():
self.pop_info()
username = driver.find_element_by_xpath("//div[@class='user_meg_con']/p[@class='userBrief']/i/a[1]").text
return username
username = functions.loop_until_notblank(find_username)
#断言用户名
self.assertNotEqual("", username)
.............
![(please configure the [header_logo] section in trac.ini)](http://www1.pconline.com.cn/hr/2009/global/images/logo.gif)