运行Playwright测试时遇ImportError:找不到pages模块求助
解决Playwright测试中ModuleNotFoundError: No module named 'pages'问题
问题场景
运行Playwright测试时触发ModuleNotFoundError: No module named 'pages'错误,但pages是已创建的合法Python包,文件夹结构和代码均严格遵循教程设置。
错误信息
ImportError while importing test module 'C:\Users\fsdam\OneDrive\Documents\python_work\playwright-python-tutorial\tests\test_search.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: C:\Users\fsdam\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) test_search.py:2: in <module> from pages.search import DuckDuckGoSearchPage E ModuleNotFoundError: No module named 'pages'
文件夹结构
. └── playwright_python_tutorial/ ├── pages/ │ ├── __init__.py │ ├── result.py │ └── search.py └── tests/ └── test_search.py
测试代码
from playwright.sync_api import expect, Page from pages.search import DuckDuckGoSearchPage from pages.result import DuckDuckGoResultPage def test_basic_duckduckgo_search(page: Page) -> None: search_page = DuckDuckGoSearchPage(page) result_page = DuckDuckGoResultPage(page) #Given the DuckDuckGo home page is displayed search_page.load() #When the user searches for a phrase page.locator('id=searchbox_input').fill('panda') #page.fill('id=searchbox_input', 'panda') page.locator('xpath=//button[@aria-label="Search"]').click() #Then the search result query is the phrase expect(result_page.search_input).to_have_value('panda') # Alternative way: assert 'panda' == page.input_value('id=search_form_input') #And the search result links pertain to the phrase assert result_page.result_link_titles_contain_phrase('panda') #And the search result title contains the phrase expect(page).to_have_title('panda at DuckDuckGo')
解决方法
方法1:手动添加项目根目录到Python路径
在test_search.py开头添加以下代码,将项目根目录(playwright_python_tutorial文件夹)加入Python搜索路径:
import sys from pathlib import Path # 获取当前文件的父目录的父目录,即项目根目录 sys.path.append(str(Path(__file__).parent.parent))
方法2:使用相对导入
修改测试文件中的导入语句为相对导入形式:
from playwright.sync_api import expect, Page from ..pages.search import DuckDuckGoSearchPage from ..pages.result import DuckDuckGoResultPage
注意:运行测试时必须从项目根目录执行命令,比如:
python -m pytest tests/test_search.py
不能直接在tests目录下运行单个测试文件。
方法3:将项目安装为可编辑包
在playwright_python_tutorial文件夹下创建setup.py文件,内容如下:
from setuptools import setup, find_packages setup( name="playwright_python_tutorial", packages=find_packages(), )
然后在项目根目录执行以下命令,将项目安装为可编辑模式:
pip install -e .
安装完成后,Python会自动识别pages包,无需修改导入语句即可正常运行测试。
内容的提问来源于stack exchange,提问作者fdama
相关产品推荐
相关产品推荐

