Skip to content
Advertisement

Is this correct way to use “switch()” method in selenium?

Aim: To count links in footer section of a webpage.

Instead of this:

WebElement footerdriver=driver.findElement(By.id("gf-BIG"));
system.out.println(footerdriver.findElement(By.tagName("a")).size());

I want to write like this:

WebElement footerdriver=driver.findElement(By.id("gf-BIG"));
driver.switch(footerdriver);
system.out.println(driver.findElement(By.tagName("a")).size());

Is this correct way to use “switch()” method in selenium ?

Advertisement

Answer

Unless I am mistaken, switch() is not a method belonging to the Selenium Webdriver. The method switchTo() is used to change your focus to a different window, tab or iframe.

If I am understanding your question you want to find an element that is descending from a different element. The way to do this is just find the element using the WebElement method findElement(By locator). E.g:

driver.get("https://www.wikipedia.org/");
WebElement eng = driver.findElement(By.xpath("//a[@id='js-link-box-en']"));
System.out.println(eng.findElement(By.tagName("span")).getText());

This will find a span element that descends from the element “eng”.

Here is a runnable example of a test using the method.

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