Reputation: 632
I have a two like like below
<body>
<a href="contact.php" target="_blank">contact</a>
<a href="test.php" target="_blank">Sest</a>
</body>
After click on link page has open in new tab , I want to close this tab without close driver, Is it possible ? I have tried below code but not working.
link = driver.find_element_by_xpath(
"//a[contains(text(),'contact') or contains(text(),'est')]")
link.click()
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
Upvotes: 2
Views: 1356
Reputation: 4572
A tab is nothing more than another window (from the eyes of selenium)
To close a window you must switch to it, then call driver.close()
.
This does NOT cause selenium to quit the driver itself, which I suspect is what you might be afraid of.
To switch to a window, you'll need the window ID.
driver.current_window_handle
gives you the window you're currently focused. driver.window_handles
will give you a list of all the windows open.
Assuming you only have two windows open, it should be easy to identify the one you want to close.
Lastly, don't forget to switch back to the original window. Closing a window does not automatically move your focus back to a window.
driver.switch_to.window(window_id)
driver.close()
driver.switch_to.window(original_id)
Upvotes: 1
Reputation: 893
You can switch between windows by using driver.window_handles
to identify all the windows currently open in your driver
's browser. Then you can move between them using `driver.switch_to_window(). Here's an example:
tabs = driver.window_handles #get list of open windows
driver.switch_to_window(tabs[1])
driver.close() #close the current window
driver.switch_to_window(tabs[0]) #return to first window
Upvotes: 3
Reputation: 82
It's like a real browser. If you close the one and only tab, the browser closes himself. Try not to open the second Tab in a new Tab, just use the other you don't want anymore.
Upvotes: 0