1

I'm new to python and selenium and I'm trying to switch between tabs, I've already tried using the normal key commands, ActionChains, and Keys.CONTROL, but it's not working, how would I do this. The program is the following

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


driver1  = webdriver.Chrome(executable_path="C:\mydriver\chromedriver")
  
ar = ['https://google.com', 'https://bing.com']
for page1 in (ar):
    driver1.execute_script(f"window.open ('{page1}')")
    time.sleep(3)

for x in range (5):
    driver1.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
  • I see one problem at this line `for page1 in (ar):` it should be `for page1 in ar:` – Patrik Nov 23 '20 at 17:11
  • You can use Selenium's `window_handles` - try https://stackoverflow.com/questions/28715942/how-do-i-switch-to-the-active-tab-in-selenium: – Ayush Garg Nov 23 '20 at 17:13
  • ah got it driver1.switch_to.window(driver1.window_handles[-1]), which goes back 1, i was trying to [1], thank you – Ahmad Hassan Nov 23 '20 at 17:26

1 Answers1

0

take a look at this guide: https://www.browserstack.com/guide/how-to-switch-tabs-in-selenium-python

But this is the key part:

#get current window handle
p = driver.current_window_handle

#get first child window
chwd = driver.window_handles

for w in chwd:
#switch focus to child window
    if(w!=p):
    driver.switch_to.window(w)
break
time.sleep(0.9)
print("Child window title: " + driver.title)
DMart
  • 2,401
  • 1
  • 14
  • 19