Search code examples
pythonselenium-webdriverassert

Verify title in selenium gives element not found even though website title is correct


Hi pretty much new to this and I've tried to verify title using selenium with python. The title im inputting is correct however the code isn't recognizing it. I've tried it 3 different ways but im either getting element not found, a string object error or the assert is failing even though the title of the page is correct. I've commented out the first 2 i've attempted but kept them in so you can see what I tried and got the error with:

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\webdrivers\chromedriver.exe")

driver.get(url="http://demostore.supersqa.com/my-account/")
driver.implicitly_wait(5)
#assert "My account - DemoStore" in driver.title
#the above assert doesnt work gives element not found
#driver.title().contain("My account - DemoStore")
#the above assert doesnt work gets string object error
try:
assert 'My account - DemoStore' in driver.title
print('Assertion test pass')
except Exception as e:
print('Assertion test failed', format(e))

Solution

  • There are 2 issues here:

    1. You have a problem with minus - sign inside the expected title content. It is not - sign there. Please copy-paste the expected title content from the web page directly to your code and it will work!
    2. You are missing indentations here.
      This should work better:
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    driver = webdriver.Chrome(executable_path="C:\webdrivers\chromedriver.exe")
    wait = WebDriverWait(driver, 20)
    
    driver.get(url="http://demostore.supersqa.com/my-account/")
    
    #assert "My account - DemoStore" in driver.title
    #the above assert doesnt work gives element not found
    #driver.title().contain("My account - DemoStore")
    #the above assert doesnt work gets string object error
    try:
        title = driver.title
        assert 'My account – DemoStore' in title
        print('Assertion test pass')
    except Exception as e:
        print('Assertion test failed', format(e))
    
    driver.quit()