3
I’ve tried everything. Here’s the thing. I open a page using selenium
and the python language, then I try to open a new tab, and then go to that new tab, then close this tab. That’s it. But in practice, the home page is loaded, the lines to open new tab (and consequently close it) are ignored, without launching any exceptions, and then it proceeds the code normally and closes the browser, as if I had not ordered to open a new tab and close it. And if there are errors in this code to open new tab and close, it should throw exception, no?
Code:
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()
Ok. But this solution has two problems 1) At least on my computer, the program is closing the current tab and leaving the new tab there. From what I understand, the guide that André wants to close is the new one. 2) A minor question: the switch_to_window method is deprecated, it has been replaced by switch_to.window
– Lucas
Exactly. I want to go to the new guide, and then close it
– André Oliveira
So, to do this just swap driver.window_handles[0] for driver.window_handles[1]. Try there
– Lucas
I edited the code to work as you want. The question was only to change the to driver.window_handles[1], since the first tab would be the tab 0.
– Guilherme Carvalho Lithg
Which error? I tested here and it worked well. Try to give an import time and take a time between loading the new tab and closing, with time.Sleep(3), for example.
– Guilherme Carvalho Lithg
When I run the code, is there a library missing? I used the following libraries, maybe more than I needed and the code looked like this: from Selenium import webdriver from Selenium.webdriver.common.action_chains import Actionchains from Selenium.webdriver.common.Keys import Keys # Opens a new tab and goes to the OS site driver.execute_script("window.open('stackoverflow.com', '_Blank')") # Changes tab driver.switch_to_window(driver.window_handles[1]) # Closes tab driver.find_element_by_tag_name('body'). send_keys(Keys.CONTROL + 'w')
– André Oliveira
It error this line: ---> 6 driver.execute_script("window.open('http://stackoverflow.com/', '_Blank')")
– André Oliveira
Guys worked, I’m sorry William, I copied your code, I put imported the libraries, but had forgotten to launch the browser. Sorry, your code did work, thank you very much!!!
– André Oliveira
No problem, André! I’m glad it worked. If possible, click the 'check' button next to the answer to mark as correct. Hug!
– Guilherme Carvalho Lithg
It’s there clicked brother! Valeuzão
– André Oliveira