A few words about Tab/Window switching/handling:

  • Always keep track of the Parent Window handle so you can traverse back later if required as per your usecase.

  • Always use WebDriverWait with expected_conditions as number_of_windows_to_be(num_windows) before switching between Tabs/Windows.

  • Always keep track of the Child Window handles so you can traverse whenever required.

  • Always use WebDriverWait with expected_conditions as title_contains("partial_page_title") before extracting the Page Title.

  • Here is your own code with some minor tweaks mentioned above:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver = webdriver.Firefox(executable_path=r'C:\WebDrivers\geckodriver.exe')
    driver.get("http://www.facebook.com/")
    print("Initial Page Title is: %s" %driver.title)
    windows_before  = driver.current_window_handle
    driver.execute_script("window.open('http://google.com')")
    WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
    windows_after = driver.window_handles
    new_window = [x for x in windows_after if x != windows_before][0]
    driver.switch_to.window(new_window)
    WebDriverWait(driver, 20).until(EC.title_contains("G"))
    print("Page Title after first window switching is: %s" %driver.title)
    driver.close()
    driver.switch_to.window(windows_before)
    WebDriverWait(driver, 20).until(EC.title_contains("F"))
    print("Page Title after second window switching is: %s" %driver.title)
    driver.quit()
    
  • Console Output:

    Initial Page Title is: Facebook – log in or sign up
    Page Title after first window switching is: Google
    Page Title after second window switching is: Facebook – log in or sign up
    

window.open will open the link in a new tab. Selenium Firefox driver doesn't have the ability to switch between tabs as there is only one window handle for both of them (unlike Chrome which has 2). If you give the window() command 'specs' parameter with width and height it will open a new window and you will be able to switch.

After opening the new window the driver is still focused on the first one, you need to switch to the new window first.

size = driver.get_window_size();
driver.execute_script("window.open('http://google.com', 'new_window', 'height=argument[0], width=argument[1]')", size['height'], size['width'])
driver.switch_to.window(driver.window_handles[1])
print(driver.title)