首页 > 解决方案 > Python 3 ModuleNotFoundError:没有名为“功能”的模块

问题描述

当我从步骤 python 文件导入页面对象模型时,我收到 ModuleNotFoundError: No module named 'features'。我正在使用 python 3 MacBook。

功能/步骤/tutorial.feature

import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from behave import *


from features.lib.pages.login_page import LoginPage

use_step_matcher("re")


@given("user is lead to the login page")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    context.browser.get("https://www.phptravels.net/login")


@when("I log in")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    page = LoginPage(context)
    page.login()

功能/lib/pages/login_page.py

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec


class LoginPage:
    locator_dictionary = {
        "email_field": (By.NAME, 'username'),
        "password_field": (By.ID, 'password'),
        "login_button": (By.CSS_SELECTOR, '.btn.btn-action.btn-lg.btn-block.loginbtn'),
        "accept_cookies": (By.ID, 'cookyGotItBtn')
    }

    def __init__(self, context):
        self.browser = context.browser

    def login(self, username="xxxxx", passwd="xxxxx"):
        b = self.browser

        WebDriverWait(b, 10).until(
            ec.visibility_of_element_located((By.ID, "cookyGotItBtn"))).click()

        b.find_element_by_name('username').send_keys(username)
        b.find_element_by_id('password').send_keys(passwd)
        b.find_element_by_css_selector('.btn.btn-action.btn-lg.btn-block.loginbtn').click()

功能/tutorial.feature

Feature: showing off behave

  Background: user is lead to the login page
    Given user is lead to the login page

  Scenario: login invalid
    When I log in

我的目录结构是:

path = /Users/fran/PycharmProjects/prueba1
path/features/tutorial.feature
path/features/__init__.py
path/features/lib/__init__.py
path/features/lib/pages/__init__.py
path/features/lib/pages/login_page.py
path/features/steps/__init__.py
path/features/steps/tutorial.py

我收到这个错误

  File "steps/tutorial.py", line 10, in <module>
    from features.lib.pages.login_page import LoginPage
ModuleNotFoundError: No module named 'features'

如果我将其导入为

from ..lib.pages.login_page import LoginPage

我明白了

  File "steps/tutorial.py", line 10, in <module>
    from ..lib.pages.login_page import LoginPage
KeyError: "'__name__' not in globals"

标签: pythonseleniumpycharmcucumberpython-behave

解决方案


你有一个 Python 搜索路径问题。需要正确设置 Python 搜索路径才能导入其他 Python 模块(未安装)。

问题:path/不在您的 Python 搜索路径中(检查:sys.pathPython 中的列表值)。

解决方案:

  • 在运行之前将“路径/”(作为绝对路径)添加到PYTHONPATH环境变量中
  • 添加一个“path/features/environemt.py”文件,通过使用将“path/”添加到 Python 搜索路径sys.path

推荐阅读