How to switch to new window in Selenium for Python? - python

I am working on selenium automation project using Python.
I am facing an issue, which is handling multiple browser windows.
Scenario is as follows. When I click a link on the home page, a new window opens. In the newly opened window I cannot perform any actions, because the focus is still on the home page web driver.
Can anybody show me how to change focus from the background window to the newly opened window?
A possible solution is driver.switch_to.window(), but it requires the window's name. How to find out the window's name? If this is a wrong way to do this, can anybody give some code examples to perform this action?

You can do it by using window_handles and switch_to.window method.
Before clicking the link first store the window handle as
window_before = driver.window_handles[0]
after clicking the link store the window handle of newly opened window as
window_after = driver.window_handles[1]
then execute the switch to window method to move to newly opened window
driver.switch_to.window(window_after)
and similarly you can switch between old and new window. Following is the code example
import unittest
from selenium import webdriver
class GoogleOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_google_search_page(self):
driver = self.driver
driver.get("http://www.cdot.in")
window_before = driver.window_handles[0]
print window_before
driver.find_element_by_xpath("//a[#href='http://www.cdot.in/home.htm']").click()
window_after = driver.window_handles[1]
driver.switch_to.window(window_after)
print window_after
driver.find_element_by_link_text("ATM").click()
driver.switch_to.window(window_before)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()

On top of the answers already given, to open a new tab the javascript command window.open() can be used.
For example:
# Opens a new tab
self.driver.execute_script("window.open()")
# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])
# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here
You're then able to close the original tab as follows
# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])
# Close original tab
self.driver.close()
# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])
Or close the newly opened tab
# Close current tab
self.driver.close()
# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])
Hope this helps.

window_handles should give you the references to all open windows.
this is what the documentation has to say about switching windows.

for eg. you may take
driver.get('https://www.naukri.com/')
since, it is a current window ,we can name it
main_page = driver.current_window_handle
if there are atleast 1 window popup except the current window,you may try this method and put if condition in break statement by hit n trial for the index
for handle in driver.window_handles:
if handle != main_page:
print(handle)
login_page = handle
break
driver.switch_to.window(login_page)
Now ,whatever the credentials you have to apply,provide
after it is loggen in. Window will disappear, but you have to come to main page window and you are done
driver.switch_to.window(main_page)
sleep(10)

We can handle the different windows by moving between named windows using the “switchTo” method:
driver.switch_to.window("windowName")
Click here to open a new window
Alternatively, you can pass a “window handle” to the “switchTo().window()” method. Knowing this, it’s possible to iterate over every open window like so:
for handle in driver.window_handles:
driver.switch_to.window(handle)

Related

Selenium script searches previous tab's HTML after opening a new tab

After opening a new tab using selenium, I tried to look for an element in the new tab – but the script is still searching on the html script from the previous tab. How do I make it so that after I open a new tab, it searches the open tab's HTML instead of a previous one's?
Below is my code (it doesn't work since I try and search for an element on the new tab, but the script searches for it on the first tab).
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Users\\jack_l\\AppData\\Local\\Google\\Chrome\\User Data")
options.add_argument(r'--profile-directory=Profile 8')
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
#Opens the Chrome browser
driver.get("https://www.beatstars.com/")
#Opens a new tab on the browser and goes to that URL
driver.execute_script("window.open('https://www.tunestotube.com/', 'new window')")
#Doesn't work since it's searching for a "tunestotube" element on "beatstars"
theText = driver.find_element(By.XPATH, "/html/body/div[2]/div[2]/div[2]").text
Any help would be greatly appreciated.
driver.execute_script("window.open('https://www.tunestotube.com/', 'new window')")
driver.switch_to.window( driver.window_handles[1])
theText = driver.find_element(By.XPATH, "/html/body/div[2]/div[2]/div[2]").text
When you open a tab you get a handle you need to switch back to the previous handle and then find your element.
Found a solution: You need to switch to the new window
Below is code that gets a website on the first tab, opens a new tab with another website, and then can read/find elements in that new tab.
#Gets a browser and sets the window to a variable
driver.get("https://www.exampleWebsiteForFirstTab.com/")
window_before = driver.window_handles[0]
#Open a new tab and sets the window to a variable
driver.execute_script("window.open('https://www.exampleWebsiteForSecondTab.com/', 'new window')")
window_after = driver.window_handles[1]
#Switches the current window to the new tab
driver.switch_to.window(window_after)
###DO WHATEVER YOU WANT IN THE NEW TAB
#Switches the current window to the old tab
driver.switch_to.window(window_before)
Hopefully this helps anyone who had the same problem I did!

selenium python - leaving pop up window hangs

I want to emulate the following behavior in selenium python (python v2.7, selenium v3.4.2, geckodriver):
Click link on the page which opens pop up window
Select link on pop up window and click it
Do something else on the main window
I have the following code:
main_window_handle = None
while not main_window_handle:
main_window_handle = driver.current_window_handle
driver.find_element_by_xpath('//*[#title="Open Search Window"]').click()
search_window_handle = None
while not search_window_handle:
for handle in driver.window_handles:
if handle != main_window_handle:
search_window_handle = handle
break
driver.switch_to.window(search_window_handle)
driver.switch_to.frame("resultsFrame")
print "Clicking results frame"
driver.find_element_by_link_text("TestResult").click()
print "Expecting window to close"
driver.switch_to.window(main_window_handle)
It works for opening pop up window, selecting frame and clicking link on that frame. Pop up is closed (which is correct) but selenium hangs after that and print statement with "Expecting window to close" never gets executed. It looks very strange especially that selenium never timeouts and keeps hanging until process is manually interrupted.
EDIT:
It looks that it can be a problem with geckodriver, I executed code with chromedriver and it worked.

how to get the element a[#id='ks-overlay-close-ks-component9045'], and the div[#id='ks-component9045'] is Popup window

Picture: there is Popup window in the html
try:
all_handles = self.driver.window_handles
for handle in all_handles:
if handle != now_handle:
print handle
try:
self.driver.switch_to_window(handle)
self.driver.find_element_by_xpath(".//*[#id='ks-overlay-close-ks-component9045']").click()
except:
continue
but it is failed, i can not switch to the window and close it
This one does not look like a browser pop up window. In this case you don't need switch_to_window and window_handles functions, just find the DOM element that represents the close button and have click on it.

Selenium Webdriver failed when use window_handles

I am trying to handle Two Tab in Python Selenium webdriver with Chrome as browser.
I am getting result for find element by link text on first tab as well as second tab if I keep the Chrome Browser as selected window.[i.e Front Screen Process ]
When I change the control to new tab using
driver.switch_to_window(driver.window_handles[1])
and minimise the google chrome[i.e if I select any process other than Google Chrome].i get the error in finding the link text saying Element Not Found Exception for Second Tab only not on first Tab.
I am getting result on First Tab.
def DriverCreation():
try:
Driver = WebBase.initWebScraping(URL) # Methods visible Driver.driver and Driver.loggerDriverWait = Driver.EC
print "Driver Creation Successful"
return Driver
except:
print "Driver Initalisation Failed"
sys.exit(1)
if __name__ == '__main__':
URL = 'https://www.example.com/'
Driver = DriverCreation() # will Load first Tab with www.Example.com
aboutlink = Driver.driver.find_element_by_link_text('about')
aboutlink.send_keys(Keys.CONTROL + Keys.RETURN)
Driver.driver.switch_to_window(Driver.driver.window_handles[1])
contactLink = Driver.driver.find_element_by_link_text('contact')
print contactLink.text() #** getting error if i change the focus from Google Chrome and works fine if i keep the window focus on Google Chrome**
you can manage tab using following code.
driver.execute_script("window.open('"+url+"', '_blank');")
driver.switch_to_window(driver.window_handles[1])

move control to newly opened IE window in selenium webdriver (using python) :no window name , no window handle ,not a alert

Setup :python bindings for selenium 2.45.0 ,IEserver driver2.45.0(x86),python 2.7.9 ,window 7 64 bit
Issue : when i click on this redirect button href= https:www.work.test.co.in:1XXX9/TEST/servlet/MainServlet/home" target="_blank"
a new window opens , unable to click anything on new window as control(focus) remains on previous window (confirmed by closing the previous window).
Tried
1.no name , so cannot try
driver.switch_to_window("windowName")
2.tried to print the handle (so that i can use handle reference ) but i can see only one window handle . used following code
for handle in driver.window_handles:
print "Handle arr = ",handle
driver.switch_to_window(handle)
3.Question1 : why i am getting only one window handle handle , i can see two IE instances in task manager.
4.i tried using index - 0 ,1 etc.
driver.switch_to_window(driver.window_handles[-1])
5.not sure of this thing though tried
driver.SwitchTo().Window(driver.WindowHandles.Last())
6.tried though i am sure that its not an alert window .
alert = driver.switch_to_alert()
SCRIPT :
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
driver = webdriver.Ie()
driver.get("https://my intranet site .aspx")
driver.implicitly_wait(2)
elem = driver.find_element_by_xpath("my xpath ")
elem.click()
driver.implicitly_wait(2)
elem = driver.find_element_by_xpath("//*[#id='tab1_2']/div[16]")
elem.click()
handle = driver.current_window_handle
print "Handle main = ",handle
driver.implicitly_wait(5)
elem = driver.find_element_by_xpath("page link button")
elem.click()
sleep(5)
my tried scenarioes here
Suggestions will be highly appreciated
Update - when new window opened directly through link URL , able to perform actions on it like clicking etc
So only issue is when I open it in continuation of first window through script.
Update : Main concern is why not getting second window handle even if task manager showing two instances of IE .
I don't know Python, but in Java I would do it in this way:
// get handles to all opened windows before the click
Set<String> handlesBeforeTheClick = driver.getWindowHandles();
// and now click on the link that opens a new window
findElement( linkThatOpensNewWindow ).click();
// then wait until a new window will be opened
wait.until( ....condition ==> handlesBeforeClick.size() < driver.getWindowHandles().size(); .... )
// then get a handle to a new window
Set<String> handlesAfterClick = driver.getWindowHandles();
handlesAfterClick.removeAll( handlesBeforeClick );
String handleToNewWindow = handlesAfterClick.iterator().next();

Categories

Resources