You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium报AttributeError: module 'pages' has no attribute 'home_page'如何解决

错误原因

你遇到的AttributeError: module 'pages' has no attribute 'home_page'错误核心是Python的包导入规则导致的:

  • 默认情况下,执行import pages时,Python只会加载pages包的根模块(即pages/__init__.py的内容),不会自动递归加载包下的所有子模块。如果你的pages/__init__.py里没有显式导入home_page、base_page这两个子模块,pages模块对象自然不会有这两个属性。
  • 额外关联问题:Python不支持类方法重载,你在BasePage中写了两个__init__方法,后者会完全覆盖前者,你预期的接收driver、config两个参数的构造方法实际无法生效。
可行解决方法

方法1:补全pages包的__init__.py显式导入子模块(最推荐)

在pages目录下的__init__.py文件中添加如下内容,显式导入所有子模块:

from . import base_page
from . import home_page

该方法不需要修改原有业务代码,同时不会触发循环导入问题,因为两个页面模块都是导入整个pages包,包的__init__导入子模块时不会重复触发顶层导入逻辑。

方法2:使用延迟导入避免导入时机问题

直接在gotoHomePage方法内部导入HomePage,不需要依赖pages包的属性挂载:

def gotoHomePage(self):
    # 方法内局部导入,不会触发循环导入
    from pages.home_page import HomePage
    self.__driver.get(self.__config[self.KV_BASE_URL])
    # 注意这里不需要传self,HomePage继承BasePage,直接传driver和config即可
    return HomePage(self.__driver, self.__config)

同时需要先修复BasePage的__init__方法,合并两个构造逻辑支持两种入参方式:

def __init__(self, config, driver=None):
    self.__config = config
    if driver is not None:
        self.__driver = driver
        return
    # 原有从config初始化driver的逻辑
    capabilities = DesiredCapabilities()
    if config[self.KV_BROWSER] == "CHROME":
        capabilities = DesiredCapabilities.CHROME.copy()
    elif config[self.KV_BROWSER] == "FIREFOX":
        capabilities = DesiredCapabilities.FIREFOX.copy()
    capabilities['platform'] = config[self.KV_PLATFORM]
    self.__driver = webdriver.Remote(
        desired_capabilities=capabilities,
        command_executor=config[self.KV_HUB_URL])

方法3:使用importlib动态导入

如果不想修改__init__.py也不想用局部导入,可以用Python标准库的importlib动态加载子模块:

import importlib
def gotoHomePage(self):
    self.__driver.get(self.__config[self.KV_BASE_URL])
    home_page_module = importlib.import_module('pages.home_page')
    return home_page_module.HomePage(self.__driver, self.__config)

内容的提问来源于stack exchange,提问作者mysti9uemirage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 11:54:01