Open and close multiple tabs in browser with Python

0

Hello, I need some help. I need this script I have (Python and JS) open a certain number of tabs and after a time interval close and reopen the same tabs again. However, in order not to close the browser I still need one of them to remain open. For the time being I'm in that code, but it's been two days since I left him. Note: I'm using Selenium!

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import json
import sys
import os
import pyautogui

sys.path.append(os.getcwd())

arquivoConf = os.path.join(os.getcwd(), sys.argv[1])

with open(arquivoConf) as json_data_file:
    config = json.load(json_data_file)

firefox_profile = webdriver.FirefoxProfile(config['from_nameFirefox'])
browser = webdriver.Firefox(firefox_profile)

num_of_tabs = 10
time.sleep(10)
while True:
    t = len(browser.window_handles)
    print (t) 
    for i in range(1,  t):
        browser.window_handles[i]
        time.sleep(2)
        print ( 'Fechando tab ' + str(i) )
        for x in range(1, num_of_tabs):
        browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
        browser.execute_script('window.open("","_self").close()')
        browser.execute_script('window.close()')
        time.sleep(2)
    
asked by anonymous 01.12.2017 / 17:52

1 answer

0

You can try this:

while True:

    num_current_tabs = len(browser.window_handles)

    # Fechar todas - 1 abas, deixando uma aberta para não fechar o navegador.
    for i in range(1, num_current_tabs):
        browser.window_handles[i]
        browser.close()
        time.sleep(2)

    # Script para abrir as páginas.
    for total_new_tabs in range(1, num_of_tabs):
        self.browser.execute_script("window.open('','_blank');")

        # Foca na última aba aberta
        browser.switch_to_window(browser.window_handles[-1]) 
        time.sleep(2)

    # Fecha a aba remanescente das anteriormente fechadas.
    browser.windows_handles[0].close()
    
04.12.2017 / 13:42