Is it possible to switch to an element in a frame without using driver.switchTo().frame(“frameName”) in Selenium Webdriver Java?

余生颓废 提交于 2019-11-26 18:01:33

In simple words,

No, it wouldn't be possible to access the elements without switching into the intended <iframe> i.e. without using driver.switchTo().frame()

To switch to the intended frame you have to use either of the following :

  • Switch through Frame Name:

    driver.switchTo().frame("frame_name");
    
  • Switch through Frame ID:

    driver.switchTo().frame("frame_id");
    
  • Switch through Frame Index:

    driver.switchTo().frame(1);
    
  • Switch through WebElement:

    driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@attribute='value']")));
    
  • Switch to Parent Frame:

    driver.switchTo().parentFrame();
    
  • Switch to Default Content:

    driver.switchTo().defaultContent();
    

But as per best practices you should always induce WebDriverWait for the desired Frame To Be Available And Switch To It as follows:

  • Switch through Frame Name:

    new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.name("frame_name")));
    
  • Switch through Frame ID:

    new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("frame_id")));
    
  • Switch through Frame cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("frame_cssSelector")));
    
  • Switch through Frame xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("frame_xpath")));
    

I don't think you can switch to a frame without using driver.switchTo.frame(),when you have a multiple frames.

But you can use the xpath as below with ID contains for dynamic frames:

"//iframe[contains(@id,'frame')]"

(or)

You can try using the src attribute of the frame in your xpath.

(or)

You can find the number of frames or iframes using below xpath, if your frame position is same:

int noofframes=driver.findelements(By.tagName(“iframe”)).size();

And using index you can switch to a particular frame and then you can try to find the elements in the frame.

driver.switchTo.frame(i);

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!