Reputation: 185
I've been searching around for answers, but I cannot get my code to work. What I would like to happen is that I can open a tab, open a new webpage, and then close that same tab. From there, once i'm done doing my work, I'd like it to quit the program. As of now, it will not open a new tab, close the new tab, and quit the application. What is doing right now, is that it opens up google, then loads stackoverflow in the same tab.
Right 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
Upvotes: 3
Views: 5962
Reputation: 52695
Try below code to get 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()
Upvotes: 3