feyZ1g
feyZ1g

Reputation: 62

Click a tag to opening new tab using Selenium

I just want the relevent <td> class to click on a tag and I must do this by opening it on a new tab. Here is my code:

x1=driver.find_element_by_class_name('no').send_keys(Keys.COMMAND + 't') 

enter image description here

Upvotes: 0

Views: 1121

Answers (2)

CEH
CEH

Reputation: 5909

One problem here is there are multiple td elements with class='no' so it is hard to tell which one you need to click. Because 2nd element in your list is highlighted, we can make the assumption you are trying to click the 2nd a link.

It sounds like you are trying to get the a element so that you can click on the link & clicking this will open a new tab. You'll need to first locate the a to click, then switch focus to the newly opened tab:

from selenium.webdriver.support.ui import WebDriverWait


# get number of currently open windows
windows_before = len(driver.window_handles)

# click link -- [2] specifies which one to click, change this to click different one
driver.find_element_by_xpath("//td[@class='no'][2]/a").click()

# wait up to 10s for new tab to open, then switch focus to new tab
WebDriverWait(driver, 10).until(lambda driver: len(windows_before) != len(driver.window_handles))

# switch to new window
driver.switch_to_window(len(driver.window_handles)-1)

The above code first stores the number of currently opened tabs using driver.window_handles. Then, once we click the 2nd a element to open event328706602.html link, we invoke WebDriverWait on number of open windows. Note that you will need to update [2] in the XPath depending on which a element you need to click.

In WebDriverWait, we wait for the number of windows to be greater than the value we previous stored, so we know the new window has been opened. Then, we switch to the new window handle by checking len(driver.window_handles) and switch to the last window_handle index the list.

Upvotes: 1

sayhan
sayhan

Reputation: 1184

Please try following :

x1=driver.find_element_by_class_name('no') 


ActionChains(driver).key_down(Keys.COMMAND).click(x1).key_up(Keys.COMMAND).perform() 

browser.switch_to.window(browser.window_handles[1])

Upvotes: 1

Related Questions