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:
^^ 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()
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)