0

So recently I have been using Selenium and Python to automate searches/go to websites. And so I looked up how to open new tabs in selenium because opening new windows every time for a search is a pain. I ended up using this code from a solution I found online

browser.execute_script("window.open('');")
time.sleep(2)
browser.switch_to.window(browser.window_handles[1])
browser.get("http://google.com")

to open a new tab. However the problem now arose that I need to close the tabs eventually. I tried using browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w') to try to close the tab but that didn't work. I also tried to use browser.close() but that just closed the entire window and the rest of the code failed. Any ideas on how to close tabs?

Here is the full code

browser=webdriver.Chrome(chrome_options=options)
browser.get("https://accounts.google.com/ServiceLogin/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=AddSession")

browser.execute_script("window.open('');")
time.sleep(2)
browser.switch_to.window(browser.window_handles[1])
browser.get("http://google.com")
searchh = browser.find_element_by_name('q')
text = "does CNN do newsletters?"

time.sleep(31)
browser.quit()
Kunwar Sodhi
  • 213
  • 2
  • 5
  • 13

1 Answers1

1

In your code you use driver.quit() instead of driver.close()

Difference between webdriver.Dispose(), .Close() and .Quit()

Sers
  • 12,047
  • 2
  • 12
  • 31