| | 1 | == python的selenium模块还不够健壮稳定(大多见于鼠标事件)的解决方法 == |
| | 2 | |
| | 3 | 当selenium将鼠标移动到注册了onmouse事件的元素上的时候,偶尔不能从弹出的层上获取到指定的元素,如下面这段代码: |
| | 4 | {{{ |
| | 5 | .......... |
| | 6 | def pop_info(self): |
| | 7 | driver = self.driver |
| | 8 | user_meg = driver.find_element_by_xpath("//div[@class='basicInfo']/dl/dd[1]") |
| | 9 | chains = ActionChains(driver) |
| | 10 | chains.move_to_element(user_meg).perform() |
| | 11 | ............. |
| | 12 | |
| | 13 | def find_username(): |
| | 14 | self.pop_info() |
| | 15 | username = driver.find_element_by_xpath("//div[@class='user_meg_con']/p[@class='userBrief']/i/a[1]").text |
| | 16 | return username |
| | 17 | }}} |
| | 18 | 我们期望能用find_username方法获得用户名,但这个方法,有时不能成功。 |
| | 19 | [[BR]] |
| | 20 | 为了解决这个问题,让find_username方法多次执行,直到成功,我们先设计一个工具方法,functions.loop_until_notblank |
| | 21 | {{{ |
| | 22 | |
| | 23 | def loop_until_notblank(fun, times = 10): |
| | 24 | ''' 循环调用fun指定的次数(times),直到返回的结果不是空串 ''' |
| | 25 | for i in range(0, times): |
| | 26 | result = fun() |
| | 27 | if result != '': |
| | 28 | return result |
| | 29 | return '' |
| | 30 | |
| | 31 | }}} |
| | 32 | 使用示例如下: |
| | 33 | {{{ |
| | 34 | ............. |
| | 35 | def find_username(): |
| | 36 | self.pop_info() |
| | 37 | username = driver.find_element_by_xpath("//div[@class='user_meg_con']/p[@class='userBrief']/i/a[1]").text |
| | 38 | return username |
| | 39 | |
| | 40 | username = functions.loop_until_notblank(find_username) |
| | 41 | |
| | 42 | #断言用户名 |
| | 43 | self.assertNotEqual("", username) |
| | 44 | ............. |
| | 45 | }}} |
| | 46 | |
| | 47 | |
| | 48 | |