SamH123 SamH123 - 1 year ago 234
Python Question

Selenium won't open a new url in a new tab (Python & Chrome)

I want to open quite a few URLs in different tabs using Selenium WebDriver & Python.

I am not sure what is going wrong:

driver = webdriver.Chrome()
url2 = ''

I looked up tutorials and it seems to me as though this code should do what I want. What actually happens is the browser opens, url1 opens as it should, a new tab opens as it should but url2 then loads in the original tab instead of the new one (even though the new tab appears to be the active one).

(I am using Chrome because when using Firefox I can't get it to load any URLs at all. Firefox opens but does not get the url requested. I have tried to find a solution to this but to no avail.)

Is there anything I can change in my code to get the new url to open in the new tab?

Thanks for your help!

Answer Source

There is a bug in ChromeDriver that prevents ctrl/command+T from working:

What you can do, as a workaround, is to open a link in a new tab and then switch to a new window using the switch_to.window(). Working sample:

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

driver = webdriver.Chrome()

# open a link in a new window
actions = ActionChains(driver)
about = driver.find_element_by_link_text('About')


Now the last driver.get() would be performed in a newly opened tab.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download