Alex Dana
Alex Dana

Reputation: 1307

How to "open in a new tab" with selenium and python?

I'm writing a bot with Python/Selenium.

In my process, I want :

I tried the following :

def OpenInNewTab(self):
        content = self.browser.find_element_by_class_name('ABCD')
        action = ActionChains(self.browser)
        action.move_to_element(content).perform();
        action.context_click().perform()
        action.send_keys(Keys.DOWN).perform()
        action.send_keys(Keys.ENTER).perform()

However, the problem is that my bot :

After a lot of researches, I tried with :

import win32com.client as comclt       
wsh = comclt.Dispatch("WScript.Shell")
wsh.SendKeys("{DOWN}")
wsh.SendKeys("{ENTER}")

However, it's not really working.

I saw many other topics, like this one (supposing there is href associated to the pic)

Then, i'm a little lost to be able to do tthis simple thing : open a righ click on contextual an element and select open in a new tab. I'm open to any advice / new road to follow.

Upvotes: 0

Views: 781

Answers (1)

0buz
0buz

Reputation: 3503

In my experience it will be difficult to achieve a perfect "one fits all" solution involving the (context menu - new tab) combination, and I tend to keep clear of all the headache it can bring.

My strategy would be a bit different, and, on a case by case basis, I'd use something like:

base_window = driver.current_window_handle  # this goes after you called driver.get(<url here>)

my_element=driver.find_element_by_xpath(...) #or whatever identification method
my_element.send_keys(Keys.CONTROL + Keys.ENTER)

driver.switch_to.window(driver.window_handles[1])  #switch to newly opened tab

driver.switch_to.window(base_window)  # switch back to the initial tab

An alternative workaround is using hrefs - first open a new tab, then load the fetched href(s). Here's an example:

url='https://www.instagram.com/explore/tags/cars/?hl=en'
driver.get(url)
base_window = driver.current_window_handle

a_tags=driver.find_elements_by_xpath("//div[@class='v1Nh3 kIKUG  _bz0w']//a")
hrefs=[a_tag.get_attribute('href') for a_tag in a_tags] #list of hrefs

driver.execute_script("window.open();")   #open new tab
driver.switch_to.window(driver.window_handles[1]) #switch to new tab
driver.get(hrefs[0])  #get first href for example
driver.close()  #close new tab
driver.switch_to.window(base_window)  #back to initial tab

Upvotes: 1

Related Questions