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.
Related
driver.find_element(By.XPATH, "//input[#name = 'SelectAll' and #value='Move All >>>']").click()
driver.find_element(By.NAME, "Submit1").click()
For background, this is part of a script that goes to a website, completes a few actions/prompts, and pulls a CSV file. The code above works most of the time but sometimes gives an error of,
UnexpectedAlertPresentException: unexpected alert open: {Alert text : No contracts have been selected.}
(Session info: headless chrome=97.0.4692.99)
This is from a page where you have to move list items over from one dialogue box to another. You receive this error when nothing has been pulled over. Also as a note, I do have an implicitly_wait(100) before this code.
I am trying to get the above code to run through a loop where it will keep repeating/retrying the code until there is a success.
If I clearly understnd what goes there:
You want to continue performing the 2 click actions you mentioned until no alert appeared.
I.e. in case alert appearing - close the alert and perform the clicks again.
In case no alert appeared - no more need to click these 2 elements, continue further with the next code.
If so you can do something like this:
while True:
driver.find_element(By.XPATH, "//input[#name = 'SelectAll' and #value='Move All >>>']").click()
driver.find_element(By.NAME, "Submit1").click()
try:
alert = driver.switch_to.alert
alert.accept()
except:
break
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.
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])
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();
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)