Daria Ivanova Daria Ivanova - 9 months ago 43
Python Question

selenium with python: driver.title is not the same as an actual page title

I wrote a code on python that has to check if the loaded page has an expected title. But after the page has been loaded the line

printed out "Google" instead of expected "dog - Google Search" which you can find on the page source (
<title> dog - Google Search </title>

Q: why driver.title is "Google" but not what we have between the title tags ("dog - Google Search")?

Here is my code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

driver = webdriver.Firefox(executable_path = "/usr/local/bin/geckodriver")
driver.get("https:www.google.com") # opens the browser
# finds an input field and paste "dog" into it and then presses "Return"
search_field = driver.find_element_by_name("q")

# waits until the title of the page appears)
WebDriverWait(driver, 100).until
EC.presence_of_element_located((By.XPATH, "/html/head/title"))


print(driver.title) # prints driver.title (in reality it prints "Google" not "dog - Google Search")

#checks if the title is "dog - Google Search"
if driver.title == "dog - Google Search":
print("It works!")
print("NO JOB YET")


Answer Source

The expected condition needs to be changed because presence_of_element_located hold true in this scenario as title remains visible since search page was opened so it doesn't really wait for title to update. Instead you should wait until text is changed in title to what is expected in expected condition as below.

WebDriverWait(driver, 10).until
   EC.text_to_be_present_in_element((By.XPATH, "/html/head/title"), "dog - Google Search")

This will poll the DOM for 10 seconds and if title match is found it will proceed to next instruction.