问题描述
要求:默认情况下,在主窗口中搜索网络元素,如果找到则执行操作,否则在iframe中搜索网络元素并执行所需的操作
Requirement: Bydefault, search for webelement on main window, if found perform action else search for webelement inside iframes and perform required action
硒3.141
'''
WebElement el = driver.findElement(By.xpath("//*[contains(text(),'here')]"));
boolean displayFlag = el.isDisplayed();
if(displayFlag == true)
{
sysout("element available in main window")
el.click();
}
else
{
for(int f=0;f<10;f++)
{
sysout("element available in frameset")
switchToFrame(frameName[f]);
el.click();
System.out.println("Webelement not displayed");
}
}
'''
我的脚本本身在第一行失败.它正在尝试在主窗口中查找元素,但该元素实际上在iframe中可用.
My script is failing at first line itself. It is trying to find element in main window but element is actually available in iframe.
但是要求是先在主窗口中搜索,然后才导航至iframe.如何处理这种用例?
But the requirement is to search first in main window and then only navigate to iframes. How to handle such usecase?
有什么建议会有所帮助吗?谢谢.
Any suggestion would be helpful? Thank you.
推荐答案
是的,如果主窗口中不存在该元素,则可以编写循环遍历所有iframe. Java实现:
Yes, you can write a loop to go through all the iframes if the element not present in the main window.Java Implementation:
if (driver.findElements(By.xpath("xpath goes here").size()==0){
int size = driver.findElements(By.tagName("iframe")).size();
for(int iFrameCounter=0; iFrameCounter<=size; iFrameCounter++){
driver.switchTo().frame(iFrameCounter);
if (driver.findElements(By.xpath("xpath goes here").size()>0){
System.out.println("found the element in iframe:" + Integer.toString(iFrameCounter));
// perform the actions on element here
}
driver.switchTo().defaultContent();
}
}
Python实现
# switching to parent window - added this to make sure always we check on the parent window first
driver.switch_to.default_content()
# check if the elment present in the parent window
if (len(driver.finds_element_by_xpath("xpath goes here"))==0):
# get the number of iframes
iframes = driver.find_elements_by_tag_name("iframe")
# iterate through all iframes to find out which iframe the required element
for iFrameNumber in iframes:
# switching to iframe (based on counter)
driver.switch_to.frame(iFrameNumber+1)
# check if the element present in the iframe
if len(driver.finds_element_by_xpath("xpath goes here")) > 0:
print("found element in iframe :" + str(iFrameNumber+1))
# perform the operation here
driver.switch_to.default_content()
这篇关于有没有一种方法可以首先在主窗口中搜索网络元素(如果找不到),然后开始在iframe中进行搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!