Open a url right after opening a new tab in the browser (Selenium)

Asked

Viewed 388 times

1

I’m making a code to access a template page of my institution.

Objective: In the first guide, I open the digital book; In the second guide, I open the template.

However, I have to do the feedback in order to enter two different links to finally be able to enter a certain discipline.

My attempt was to do the following: (Example with overflow)

from time import sleep
from selenium import webdriver


driver = webdriver.Firefox()

btlivro = driver.get("https://answall.com") # Primeira guia
sleep(3)
driver.execute_script("window.open('/questions')") # Segunda Guia
sleep(3)
btdisciplina1 = driver.get("/questions/ask")

But what really happens is that the url inside btdisciplina1 is accessed inside the first tab, not the second tab I just opened.

In short: How can I do to the url inside btdisciplina1 be accessed in the second tab?

  • You can control the access of tabs as it was through the keyboard, Ctrl + t (new tab) Ctrl +1 access first tab Ctrl + 2 access the second tab opened. send_keys. Selenium has this control using the following syntax Keys.CONTROL + ’t' :new tab... access the first tab Keys.CONTROL + '1) using the import syntax from Selenium.webdriver.common.Keys import Keys send_keys(Keys.CONTROL + '1'

  • For some reason, this is not working in my program. body = driver.find_element_by_tag_name("body") jumps line body.send_keys(Keys.CONTROL + 't') )

1 answer

0


After almost 3 days, I ended up getting, through the window_handles method.

This was my solution (commented) using the guidelines' indices, I hope it helps everyone who goes through the same problem.

from time import sleep
from selenium import webdriver


driver = webdriver.Firefox()

buttomLivro = driver.get("https://answall.com") # Abre primeira guia
sleep(1)
window_before = driver.window_handles[0] # Chama a primeira guia de "windows_before"

driver.execute_script("window.open('/questions')") # Abre segunda guia
sleep(1)
window_after = driver.window_handles[1] # Chama a segunda guia de "windows_after"

driver.switch_to.window(window_after) # Troca para a segunda guia
sleep(1)
buttomGabarito = driver.get("/questions/ask") # Acessa o link na segunda guia

Browser other questions tagged

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