Selenium自动化测试切换iframe时报ChangeBookingPage无switch_to属性如何解决
报错触发原因
本次报错的核心原因是 switch_to 属于Selenium原生WebDriver实例的内置属性,自定义的ChangeBookingPage页面对象本身没有内置该属性,同时Element类的iframe切换逻辑存在调用错误:
- 从Element类的实现可见,
switch_to_iframe方法直接执行self.page.switch_to.frame(self.locator),此处的self.page指向ChangeBookingPage类的实例,该实例没有暴露switch_to属性,直接调用就会触发属性不存在的报错 - 你已经在
fbdriver.py中封装了switch_to_iframe方法专门处理iframe切入逻辑,但Element层的方法没有调用该已封装的能力,反而直接调用了不存在的属性
修复方案
推荐选择改动最小的方案:修改Element类的switch_to_iframe方法逻辑,直接调用页面对象封装好的iframe切换方法即可:
# 修改element.py文件中的switch_to_iframe方法 def switch_to_iframe(self): # 替换原有直接调用switch_to的逻辑,调用已封装的切换方法 self.page.switch_to_iframe(self.locator)
如果你的页面对象没有直接继承FbDriver的方法,也可以选择在ChangeBookingPage类中透传WebDriver的switch_to属性:
# 在ChangeBookingPage类的初始化方法中添加透传逻辑 def __init__(self, driver): self.driver = driver # 新增下行代码,把driver的switch_to属性暴露给页面对象 self.switch_to = self.driver.switch_to
内容的提问来源于stack exchange,提问作者DK26
相关产品推荐
相关产品推荐

