Skip to content
Advertisement

How to open a link without knowing its URL in new tab using python selenium

I wanted to click a link in facebook group post which has href attribute as “#” but when we click on it that href attribute will automatically change to particular URL so I just wanted to click on link so that it will open in new tab.

Sorry I don’t have any code to explain this scenario.

Advertisement

Answer

Since you didn’t provide nor code nor a link to that page I answered it with some example code on how to open a link in a new tab:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
actions = ActionChains(driver)
driver.get("https://stackoverflow.com/")
link = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, "//a[@class='s-navigation--item js-gps-track']")))
actions.key_down(Keys.CONTROL)
actions.click(on_element=link)
actions.perform()

Anyway this is it: you use ActionChains to control+click (open in new tab) the link. With that you can perform every complex operation. A list of available actions/methods can be found here.

EDIT: Ah, if then (I guess) you want to move from a tab to another you can easily do it like this:

tabs = driver.window_handles
driver.switch_to.window(tabs[1])

Where tabs is a zero-based list (tabs[0] is the first tab, tabs[1] the second and so on…)

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement