1

I am trying to get an xpath for a certain button/Frame. I am able to locate the element using the xpath but while running automation I am getting element not found exception. I tried to switch to the particular frame and then finding the button but it did'nt work. Attaching the link for the page and Image. Link : https://www.msn.com/en-in/weather/today/New-Delhi,Delhi,India/we-city-28.608,77,201?iso=IN enter image description here

Here is the code I tried.

WebDriverWait wait = new WebDriverWait(cdriver,30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='foot']//following::iframe[@style='width:9.7rem;']")));
System.out.println("Ive waited for the frame to load");
int size = cdriver.findElements(By.tagName("iframe")).size();
System.out.println(size);

/*for(int i=0; i<=size; i++){
cdriver.switchTo().frame(i);
System.out.println("Switched to frame "+i);
int total=  cdriver.findElements(By.xpath("//*[@id='u_0_0']/div/button/span")).size();
System.out.println(total);
cdriver.switchTo().defaultContent();
}*/

cdriver.switchTo().frame(2);
System.out.println("Switched to frame");

cdriver.findElement(By.xpath("//*[@id='u_0_0']/div/button/span")).click();

Getting the number of frames present and then checking in each for the element but its not able to switch to the frame.

Guy
  • 46,488
  • 10
  • 44
  • 88
Ashutosh Das
  • 31
  • 1
  • 7

2 Answers2

0

To access the desired elements as the the desired elements are within an <iframe> so you have to:

  • Induce WebDriverWait for the desired frameToBeAvailableAndSwitchToIt().
  • You can use either of the following Locator Strategies:

    • Using CSS_SELECTOR:

      driver.get("https://www.msn.com/en-in/weather/today/New-Delhi,Delhi,India/we-city-28.608,77,201?iso=IN")
      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[src^='//www.facebook.com/plugins/like']")));
      
    • Using XPATH:

      driver.get("https://www.msn.com/en-in/weather/today/New-Delhi,Delhi,India/we-city-28.608,77,201?iso=IN")
      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[starts-with(@src, '//www.facebook.com/plugins/like')]")));
      

Here you can find a relevant discussion on Ways to deal with #document under iframe

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

When you used switchTo().frame(2) you actually switched to the third <iframe>. You can use switchTo().frame(1), but better choice will be to use unique identifier rather than index

WebElement iframe = cdriver.findElement(By.csSelector("#fbcount > iframe"));
cdriver.switchTo().frame(iframe);

To wait for a frame to load use frameToBeAvailableAndSwitchToIt, not elementToBeClickable

wait.until(ExpectedConditions.elementToBeClickable(By.csSelector("#fbcount > iframe")));
System.out.println("Switched to frame");
Guy
  • 46,488
  • 10
  • 44
  • 88