Python – Use Selenium to open tabs, close tabs, and quit Firefox on Mac?

Use Selenium to open tabs, close tabs, and quit Firefox on Mac?… here is a solution to the problem.

Use Selenium to open tabs, close tabs, and quit Firefox on Mac?

I’ve been looking around for answers, but my code isn’t working. What I want to happen is that I can open a tab, open a new web page, and then close the same tab. From there, once I’m done with my work, I want it to quit the program. As of now, it does not open new tabs, close new tabs, and exit applications. What is being done now is to open Google and load StackOverflow in the same tab.

Now, I have….

driver = webdriver. Firefox()
driver.get("https://www.google.com")
time.sleep(5)
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
time.sleep(5)
driver.get("https://www.stackoverflow.com")
time.sleep(5)
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 'w')
time.sleep(5)
driver. Dispose()

Does anyone have any ideas?

Thanks

Solution

Try the following code to get the desired result:

driver = webdriver. Firefox()
driver.get("https://www.google.com")
# Get current window/tab ID
current_window = driver.current_window_handle
# Open StackOverflow in new window/tab
driver.execute_script("window.open('https://www.stackoverflow.com')")
# Get new window/tab ID
new_window = [window for window in driver.window_handles if window != current_window][0]
# Switch to new window/tab
driver.switch_to.window(new_window)
# Close new window/tab
driver.close()
# Switch to initial window/tab
driver.switch_to.window(current_window)
# Quit Webdriver
driver.quit()

Related Problems and Solutions