Open and close multiple tabs in your browser with Python



  • Hi, I need a hand. I need this script that I have (Python and JS) to open a certain number of tabs and after a close time interval and reopen the same tabs again. But not to close the browser, I still need one of them to be open. For an hour I am in this code but for two days I have not left it. 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)



  • You can try this way:

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




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2