Open and close multiple tabs in Python browser

Asked

Viewed 4,733 times

0

Hi, I need some help. I need this script I have (Python and JS) to open a certain number of tabs and after a time interval close and reopen the same tabs again. However, to not close the browser, I still need to always open one of them. For now I am in this code but for two days I have not left it. Note: I am 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)

2 answers

0

You can use keyboard shortcuts to create tabs and close. For example: Control+T to open a new tab and Control+W to close.

To do this in Lenium, simply:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.google.com/")

# Abre uma nova aba
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't') 

# Carrega a nova aba
driver.get('http://stackoverflow.com/')

# Fecha a aba
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w') 


driver.close()

0

You can try it 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()
  • Thank you friend for your attention but this code is not yet doing what I want. Actually I think it was my mistake because I need it to open several tabs or tabs in the same browser window. Not in multiple windows as shown. I am currently using this code (https://pastebin.com/XRHgmprS) if you can help I would appreciate it very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.