OPENING A NEW TAB WITH SELENIUM + PYTHON + FIREFOX + UBUNTU

So this was super duper hard and I believe the reason why is because technically the browser settings and the user choices impact whether or not a clicked link opens in a fresh new tab or a fresh new window. Keep that in mind in case you have other headaches. It may be impossible (so I’ve read online) to perfectly control whether a tab opens on your users’ browser, however, since web automation is probably your browser you should be able to work with this solution and your browser settings to get it going.

Another important thing before you begin here. This assumes you are ‘right clicking an element on a page and opening in a new tab’ kind of thing. If you are trying to make a new, unrelated link open in a new tab, this doesn’t work. I’ll figure that out maybe in another blog post. This one takes a page element already in focus and then opens that into a new tab.

Final note: I’m using Ubuntu so not sure if you need to adjust for yourself…

Anyway, here comes the code.

# Import your stuffs
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# Set path to your executable Firefox` 
ffpath = '/home/wt/Documents/Waynes_Python_Education_Directory/Automation_Browser_Drivers'

# Turn your Firefox browser into a usable object (or something like that)
driver = webdriver.Firefox(ffpath)

# Come up with a creative new URL to go to (this one is great, btw)
driver.get("https://www.engrish.com/")

# Wait for a while to enjoy it..
time.sleep(5)

# Come up with a creative new URL to go to (this one is great, btw)
new_url = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div/div[2]/div[1]/div[1]/ul/li[6]/a")

# And now, the magic!  Open fun URL in a new Firefox tab!
new_url.send_keys(Keys.CONTROL + Keys.RETURN)

# Wait for a while to enjoy it..
time.sleep(5)

# Shut 'er down and go home for the day...
driver.quit()
Tags : ,

0 thoughts on “OPENING A NEW TAB WITH SELENIUM + PYTHON + FIREFOX + UBUNTU”

Leave a Reply

Your email address will not be published. Required fields are marked *