从另一个文件夹的文件导入类

import a class from a file from another folder

提问人:Urooba Shahid 提问时间:11/17/2023 最后编辑:Urooba Shahid 更新时间:11/17/2023 访问量:34

问:

我最近开始使用 Selenium 和页面对象模型,如果我不将文件划分为文件夹类tests_scripts,该程序可以正常工作。程序的流程如下所示:

\parentDirectory
    \object
       -test.py
    \pages
       -login_page.py

这是测试脚本:

from selenium import webdriver
from pages.login_page import LoginPage
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Initialize WebDriver (Chrome in this example)
driver = webdriver.Chrome()

# Open Adactin Hotel App login page
driver.get("http://adactinhotelapp.com/")

# Instantiate LoginPage
login_page = LoginPage(driver)

# Enter credentials using LoginPage methods
login_page.enter_username("------")
login_page.enter_password("------")

# Click login using LoginPage method
login_page.click_login()

# Wait for the page to load after login (example wait until the title changes)
WebDriverWait(driver, 10).until(EC.title_contains("AdactIn.com - Search Hotel"))

# Perform further actions, assertions, or navigate to other pages using other Page Objects as needed

# Example: Get the current URL after login
current_url = driver.current_url
print("Current URL after login:", current_url)

# Close the browser window
driver.quit()

这是login_page:

from selenium.webdriver.common.by import By

class LoginPage:
    def __init__(self, driver):
        self.driver = driver
        self.username_field = (By.ID, "username")
        self.password_field = (By.ID, "password")
        self.login_button = (By.ID, "login")

    def enter_username(self, username):
        self.driver.find_element(*self.username_field).send_keys(username)

    def enter_password(self, password):
        self.driver.find_element(*self.password_field).send_keys(password)

    def click_login(self):
        self.driver.find_element(*self.login_button).click()

我收到的错误:

    from pages.login_page import LoginPage
ModuleNotFoundError: No module named 'pages'

我尝试过的其他解决方案:

1st alternative:from ..pages.login_page import LoginPage

2nd alternative:import sys
                sys.path.append('/Users/path/adactin/object/')  
                from pages.login_page import LoginPage

我得到的错误:

alternative1 error:
    from ..pages.login_page import LoginPage
ImportError: attempted relative import with no known parent package

alternative2 error:
    from pages.login_page import LoginPage
ModuleNotFoundError: No module named 'pages'
python 文件 selenium-webdriver 本地存储 sys

评论


答:

0赞 Leo 11/17/2023 #1

尝试以下作为简单的技巧(您尝试了类似的东西,但排除了“页面”目录):

import sys
from pathlib import Path
sys.path.append(Path("..")/"pages")
from login_page import LoginPage

当然,另一种方法是正确打包您的项目,例如:

  1. https://betterscientificsoftware.github.io/python-for-hpc/tutorials/python-pypi-packaging/
  2. https://packaging.python.org/en/latest/tutorials/packaging-projects/