5

I'm trying to make a program that opens multiple websites, but I can't get it to press control-t. I've tried multiple solutions, but I can't find one that works. When I do the keydown method, I get an error that says

webdriver has no attribute key_down

and when I try send_keys(Keys.CONTROL + 't') it doesn't raise any errors, or do anything. How can I open a new tab?

Here's my try :

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://youtube.com")
search = driver.find_element_by_id("search")
#search.keydown(Keys.CONTROL)

#Webelement.key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()

search.send_keys(Keys.CONTROL+'t')
time.sleep(10)
imxitiz
  • 3,920
  • 3
  • 9
  • 33
GOODTOAD
  • 77
  • 1
  • 5

4 Answers4

6

You can do it as

from selenium import webdriver

driver.get("https://www.youtube.com")
search = driver.find_element_by_id("search")

driver.execute_script("window.open('https://www.google.com')")
imxitiz
  • 3,920
  • 3
  • 9
  • 33
YaDav MaNish
  • 1,260
  • 2
  • 12
  • 20
2

Here's what you can try :

from selenium import webdriver

webBrowser = webdriver.<>()
  
# This is first tab
webBrowser.get('<>')

# Second tab
webBrowser.execute_script("window.open('about:blank','secondtab');")
webBrowser.switch_to.window("secondtab")
webBrowser.get('<>')

# Third tab
webBrowser.execute_script("window.open('about:blank','thirdtab');")
webBrowser.switch_to.window("thirdtab")
webBrowser.get('<>')

You can learn more about it from Python – Opening multiple tabs using Selenium

Additionally I think you also have you look here.

However, if you want to run something on multiple windows, then I recommend having multiple instances of webdriver. It is much easier to manage, and is supported (There are workarounds on opening a new tab/window, such as pressing a hotkey that opens a new window, but they aren't supported).

imxitiz
  • 3,920
  • 3
  • 9
  • 33
1

You can use pyautogui to doy to open new tab using ctrl+t :

import pyautogui

pyautogui.keyDown('ctrl')
pyautogui.press('t')
pyautogui.keyUp('ctrl')
imxitiz
  • 3,920
  • 3
  • 9
  • 33
farhan jatt
  • 509
  • 1
  • 8
  • 31
1
driver.switch_to.new_window()

From the webdriver docs

You can pass in 'tab' or 'window'. For ChromeDriver, it opens a tab by default.

David Gilbertson
  • 4,219
  • 1
  • 26
  • 32