Home > Software design >  What is the best way to click on a tab using Java and selenium on a webpage?
What is the best way to click on a tab using Java and selenium on a webpage?

Time:10-02

I am new to Selenium but I have a question. On the URL

I want to click the tab "Nyckeltal" (at top of the page) with the
element:

<a class="instrument-table-tab-menu__tab js_tab-menu__tab" data-target="table_2">Nyckeltal</a>.

Currently I can click the tab using the code:

String xpath ="/html/body/div/div[4]/div/div[4]/div[1]/div[1]/nav/a[3]"; 
driver.findElement(By.xpath(xpath)).click();

But I guess there is a better way to do this? I guess the path is regular changed because of ads and therefor I think using xpath is not particular good.

My question is there a better way to click "Nyckeltal" than using xpath with Selenium and if there is, how do I write?

CodePudding user response:

You can use below xPath to click that tab.

//a[contains(@class,'instrument-table-tab-menu') and text()='Nyckeltal']

In these type of cases, you need to create a dynamic xPath that means same xPath can be used for multiple element with different values.

Examples: In below examples I have just changed the text of the tab.

xPath for Kurser tab.

//a[contains(@class,'instrument-table-tab-menu') and text()='Kurser']

xPath for Historik tab.

//a[contains(@class,'instrument-table-tab-menu') and text()='Historik']

I would suggest you to practice with xPath more. Please go through this tutorial

CodePudding user response:

Very easy to do if you have the class name with:

driver.findElement(By.className("PUT CLASSNAME OF ELEMENT HERE")).click();

CodePudding user response:

You should give more precedence to css selector than xpath

CSS would be :

a[class^='instrument-table-tab-menu'][data-target$='2']

XPATH would be :

//a[contains(@class,'instrument-table-tab-menu') and contains(@data-target,'2')]

There are basically 4 ways to click in Selenium.

Using XPATH

Code trial 1 :

time.sleep(5)
driver.find_element_by_xpath("//a[contains(@class,'instrument-table-tab-menu') and contains(@data-target,'2')]").click()

Code trial 2 :

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@class,'instrument-table-tab-menu') and contains(@data-target,'2')]"))).click()

Code trial 3 :

time.sleep(5)
button = driver.find_element_by_xpath("//a[contains(@class,'instrument-table-tab-menu') and contains(@data-target,'2')]")
driver.execute_script("arguments[0].click();", button)

Code trial 4 :

time.sleep(5)
button = driver.find_element_by_xpath("//a[contains(@class,'instrument-table-tab-menu') and contains(@data-target,'2')]")
ActionChains(driver).move_to_element(button).click().perform()

Imports :

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