问题
I have a multiple nested frames and I need to access the elements under these. As these frames are dynamic I am not able to access these elements.
Is it possible for me to access the elements without using driver.switchTo().frame()
?
Like using the xpath directly or jquery, javascript or anything? Any suggestions are welcome
回答1:
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")));
回答2:
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.
来源:https://stackoverflow.com/questions/47467518/is-it-possible-to-switch-to-an-element-in-a-frame-without-using-driver-switchto