Skip to content Skip to sidebar Skip to footer

Can't Open A New Firefox Tab With Python And Selenium

I have multiple FireFox profiles and I want to open a profile, open a few tabs with diffrent URLs, open another profile open tabs with URLs. For some reason send_keys does not seem

Solution 1:

Try to open new tab using script instead of Ctrl + t keys, then change the focus using switch_to_window function.

from selenium import webdriver
import time

p1 = webdriver.FirefoxProfile(profile_directory="C:/Users/User/AppData/Roaming/Mozilla/Firefox/Profiles/4yopmm8r.py")
driver = webdriver.Firefox(firefox_profile=p1)
driver.get("https://www.reddit.com/")
time.sleep(5)
# Open a new window# This does not change focus to the new window for the driver.
driver.execute_script("window.open('');")
time.sleep(3)
# Switch to the new window
driver.switch_to_window(driver.window_handles[-1])
driver.get("https://www.stackoverflow.com/")

or try to use your original code, but use send_keys(Keys.CONTROL + "T") (capital) instead of send_keys(Keys.CONTROL + "t").

Solution 2:

If CTRL+t isn't working for you try the following:

driver.get("https://www.reddit.com/")
windows_before  = driver.current_window_handle
driver.execute_script("window.open('https://www.stackoverflow.com/')")
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
windows_after = driver.window_handles

Then, if you want to switch back to the original tab,

new_window = [x for x in windows_after if x != windows_before][0]
driver.switch_to_window(new_window)

Solution 3:

You can open the tab using the execute_script. Here is the sample code.

#navigate to reddit in base tabdriver.get("https://www.reddit.com/")
time.sleep(5) # actually you can wait for one of the element present status.
base_tab = driver.window_handles[0]

#open the new tab and navigate to SOdriver.execute_script("window.open('https://www.stackoverflow.com/')")
latest_tab = driver.window_handles[-1]

# use .swith_to.window to access the desired tab
driver.switch_to.window(base_tab)
driver.switch_to.window(latest_tab)

Other way to access the tab by index Using driver.window_handles, which will give you the list of windows. Now you can choose the tabs by index (starts with 0)

# base tab
driver.switch_to.window(driver.window_handles[0])
# second tab
driver.switch_to.window(driver.window_handles[1])
# latest tab
driver.switch_to.window(driver.window_handles[-1])

It's important to make sure the first window is loaded completely before opening the new tab, otherwise the window_handles does not match the order you expect. Because window_handles will consider the tab only once it's completely loaded.

Post a Comment for "Can't Open A New Firefox Tab With Python And Selenium"