Home > Software design >  Is this correct way to use "switch()" method in selenium?
Is this correct way to use "switch()" method in selenium?

Time:03-07

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 ?

CodePudding user response:

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.

CodePudding user response:

driver.switchTo();

should only be used to either switch to

  1. iframes/frame/frameset
  2. newly windows/tabs
  3. Alerts
  4. defaultContents

therefore,

WebElement footerdriver=driver.findElement(By.id("gf-BIG"));
driver.switch(footerdriver);

this is wrong since you are saying that you want to switch to a web element.

Also in selenium it is switchTo() not switch.

  • Related