-1
base_handle = browser.current_window_handle
#some action to open another window
if len(browser.window_handles) == 2:
    new_window_handle = browser.window_handles[1]

Now when I print both of these handles, it works great most of the time, however, once in a while the handles are same for both windows. And I am not able to solve it. Let me know if I need to share more

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • You could collect the window handles every time when opening a new tab/window, then execute the `switch_to_window` method to move to the window you want. You could refer to [this answer](https://stackoverflow.com/questions/10629815/how-to-switch-to-new-window-in-selenium-for-python/29982298#29982298) about switching between old and new windows. – Yu Zhou Mar 03 '20 at 06:17
  • Thanks Yu. However, I am doing that already, also, what the other person has recommended in this thread below. It not that the code is not working, it works. My question why out of 10 times 1 or 2 times the handle for base and new window is same? – Salman Khan Mar 04 '20 at 00:33
  • Then I think you should add breakpoints in your code and check the code line by line to see if there's any difference when the issue occurs, like when collecting the window handles. Or if the handles are the same, then reopen the window. – Yu Zhou Mar 04 '20 at 02:36

1 Answers1

1

The order of the handles in browser.window_handles is not guaranteed. You need to add a check before switching

base_handle = browser.current_window_handle
for handle in browser.window_handles:
    if handle != base_handle:
        new_window_handle = handle
Guy
  • 46,488
  • 10
  • 44
  • 88