Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't open a new Firefox tab with Python and selenium [duplicate]

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 to work, but window.open does. This is my code, so far.

import os
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
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)
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + "t")
driver.get("https://www.stackoverflow.com/")

All it does is open reddit, wait 5 seconds and then open stackoverflow. How do I fix this?

like image 390
kufte Avatar asked Nov 26 '25 03:11

kufte


1 Answers

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)
like image 143
C. Peck Avatar answered Nov 28 '25 16:11

C. Peck