I have recently started working with Selenium and the page object model, the program works fine if I don't divide the files into folders class-tests_scripts. the flow of the program looks like this:
\parentDirectory
\object
-test.py
\pages
-login_page.py
this is the test script:
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()
this is the 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()
the error i am getting:
from pages.login_page import LoginPage
ModuleNotFoundError: No module named 'pages'
the other solutions i have tried:
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
the errors i got:
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'
try the following as a simple hack (you tried something similar but excluded the "pages" directory):
Of course the other way would be to properly package your project, see for example: