'python selenium driver.switch_to.frame() suddenly failed at the second time to locate the same frame

I have composed a mini program of selenium to automate something. at the first time, below code is running perfect:

driver.switch_to.window(main_window)
driver.switch_to.parent_frame()
driver.switch_to.frame('content01')
driver.find_element_by_xpath('//*[@id="ckzx"]/div[7]/a').click()
time.sleep(0.5)
for handle in driver.window_handles:
    driver.switch_to.window(handle)
    if "return task" in driver.title:
        driver.refresh()
        time.sleep(2)
        task_window = driver.current_window_handle
        print('task_window')
        print(task_window)
        break

driver.switch_to.frame("leftFrame")
return_tasks = driver.find_elements_by_link_text('return tasks')

then I add some tasks into the task_window. Which the tasks can be manipulated in the 'leftFrame'. But it failed at the second time:

driver.switch_to.window(task_window)
driver.refresh()
time.sleep(5)
driver.switch_to.frame('leftFrame')  ### failed at this line

And the ERROR info is as below:

Traceback (most recent call last):
File "D:\Py\2_d\2_d.py", line 719, in <module>
driver.switch_to.frame('leftFrame')   ## failed at this line
   File "C:\Users\louis\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\switch_to.py", line 82, in frame
      frame_reference = self._driver.find_element(By.ID, frame_reference)
    File "C:\Users\louis\AppData\Local\Programs\Python\Python39\lib\site-      packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
      return self.execute(Command.FIND_ELEMENT, {
    File "C:\Users\louis\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
      self.error_handler.check_response(response)
    File "C:\Users\louis\AppData\Local\Programs\Python\Python39\lib\site-      packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
      raise exception_class(message, screen, stacktrace)
  selenium.common.exceptions.TimeoutException: Message: timeout: Timed out receiving       message from renderer: 300.000
    (Session info: chrome=86.0.4240.198)

Background: the failure occurs suddenly, which I mean is it's normal several days before, then, suddenly, someday, it occurs, and never gone. I don't know why.



Solution 1:[1]

You need to switch to default content first before switching to the left frame.

Code:

driver.switch_to.window(task_window)
driver.refresh()
time.sleep(5)

driver.switch_to.default_content()

driver.switch_to.frame('leftFrame')  

the reason behind that is that you are already in content01 frame and driver has focused on it so in order to switch to left frame it should set to default content and then switch.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cruisepandey