0

I am working with selenium in python. Currently, I have written a script that opens a new tab from one of the search results of Google. The associated code is as follows:

from time import sleep
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from python_file.crawler.browser import Browser

browser = Browser(0).getBrowser()
browser.get('https://www.google.com?q=python#q=python')
first_result = WebDriverWait(browser, 15).until(lambda browser: browser.find_element_by_class_name('rc'))
first_link = first_result.find_element_by_tag_name('a')

# Save the window opener (current window)
main_window = browser.current_window_handle

# Open the link in a new window by sending key strokes on the element
first_link.send_keys(Keys.SHIFT + Keys.RETURN)

# Get windows list and put focus on new window (which is on the 1st index in the list)
windows = browser.window_handles
print("opened windows length: ", len(windows))
browser.switch_to.window(windows[1])

# do whatever you have to do on this page, we will just got to sleep for now
sleep(3)

# Close current window
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')

# Put focus back on main window
browser.switch_to.window(main_window)

But I am getting an exception in the following line.

windows = browser.window_handles
print("opened windows length: ", len(windows))
browser.switch_to.window(windows[1])

As no of the window is 2, so I think windows[1] are valid. Why am I getting this exception?

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/sultan/Desktop/pycharm-2019.3.1/plugins/python/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "/home/sultan/Desktop/pycharm-2019.3.1/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/sultan/PycharmProjects/Gender_Identification_Admin/python_file/crawler/apatoto/sustho.py", line 20, in <module>
    browser.switch_to.window(windows[1])
IndexError: list index out of range
Christopher Marlowe
  • 2,098
  • 6
  • 38
  • 68

1 Answers1

1

The best way to avoid this kind of issue is the following:

  • use a loop counter with condition for the number of windows + sleep
  • when condition returns true then do the switch to the last window in the list
  • you can customize the loop to set it with a default timeout and the total loops would the default timeout/each loop sleep (usually 0.5 or 1 seconds)
lauda
  • 4,153
  • 2
  • 14
  • 28