pythonpython-3.xseleniumselenium-webdriver

Open and close Firefox tabs and switch focus via selenium in Python 3


I'm searching for a Python 3 script, which can open and close Firefox tabs and switching their focus. I'm using a Raspberry Pi 4 with the up-to-date Raspbian.

The browser will show up a very RAM hungry Grafana dashboard (the Facebook and google urls are just an example here). To keep my Raspberry alive, I have to clean up the RAM about every hour. The only suitable solution seems to close the Firefox tab with Grafana dashboard inside and open it again.

To do this as fast and nice as I can, I don't want to restart the whole browser but I just want to close the old task and open a new one. This seems to work. But my problem is that I can not switch between the tabs after creating them. So when I create a new tab, the focus will immediately switch to the new tab. Therefore the user can see the new dashboard loading. It would be better, if the new tab would load in the background and take effect when it has finished loading.

The process should be like this:

  1. Open Firefox with one tab
  2. Do nothing until a critical RAM usage is achieved
  3. Create a new Firefox tab
  4. Immediately switch the focus from the new tab to the older one
  5. Wait for a few seconds until the new tab has loaded
  6. Switch the focus to the new tab
  7. Close the old tab

^^ Go back to point 2 ^^

Python.ph

#!/usr/bin/env python
import time
import psutil
from selenium import webdriver

dr = webdriver.Firefox()

## (1)
dr.get('http://google.com‘)

while True:
    time.sleep(10)

    psutil.virtual_memory()
    dict(psutil.virtual_memory()._asdict())
    ram = psutil.virtual_memory().available * 100 / psutil.virtual_memory().total
    
    ## (2)
    if ram <= 50:
        ## (3)
        dr.execute_script("$(window.open('http://facebook.com‘))“)
        
        ## (4)
        # HOW TO SWITCH FOCUS TO THE: Older tab?

        ## (5)
        # Wait until the new tab is loaded
        time.sleep(5)
    
        ## (6)
        # HOW TO SWITCH THE FOCUS TO THE: Newer tab?
        
        ## (7)
        # Close the older tab
        dr.close()

Solution

  • To switch to the last, recently open, tab you can use this:

    last_window = driver.window_handles[-1]
    driver.switch_to.window(last_window)
    

    Similarly, to switch to the first window you can use this:

    first_window = driver.window_handles[0]
    driver.switch_to.window(first_window)
    

    Generally, if you have n open tabs you can switch to n-th tab with

    nth_window = driver.window_handles[n-1]
    driver.switch_to.window(nth_window)