Search code examples
pythonseleniumselenium-webdriverselenium-chromedriverwebdriverwait

Cannot run selenium test


I am new to automation testing. Currently downloaded selenium 4 and trying to automate login into a sample site.Please help me with this. Been struggling all day in this. And I can't even understand my error messages in the consoleenter image description here

Here is the code that I am trying to work with:

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome("/Users/prashantmishra/Documents/chromedriver")
driver.get("https://opensource-demo.orangehrmlive.com/")

driver.find_element(By.NAME, "username").send_keys("Admin")
driver.find_element(By.NAME, "password").send_keys("admin123")
driver.find_element(By.CLASS_NAME, "oxd-button oxd-button--medium oxd-button--main orangehrm-login-button").click()

captured_page_title = driver.title
expected_age_title = "OrangeHRM"

if captured_page_title == expected_age_title:
    print("Test PASSED!")
else:
    print("Test FAILED!")

driver.close()

Solution

  • You need to wait for the elements to be loaded on the web page.
    The best approach to do that is to use WebDriverWait expected_conditions explicit waits.
    Also, I improved the validation you entered the web site by validation the Dashboard title is visible.
    The following code works

    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    options = Options()
    options.add_argument("start-maximized")
    
    webdriver_service = Service('C:\webdrivers\chromedriver.exe')
    driver = webdriver.Chrome(options=options, service=webdriver_service)
    wait = WebDriverWait(driver, 10)
    
    url = "https://opensource-demo.orangehrmlive.com/"
    driver.get(url)
    
    wait.until(EC.element_to_be_clickable((By.NAME, "username"))).send_keys("Admin")
    wait.until(EC.element_to_be_clickable((By.NAME, "password"))).send_keys("admin123")
    wait.until(EC.element_to_be_clickable((By.TAG_NAME, "button"))).click()
    wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "oxd-topbar-header-title")))
    

    The result screen is:

    enter image description here