gpt4 book ai didi

java - 有没有办法先在主窗口上搜索 webelement,如果找不到,然后开始在 iframe 内搜索?

转载 作者:行者123 更新时间:2023-12-01 17:45:45 24 4
gpt4 key购买 nike

要求:默认情况下,在主窗口上搜索 webelement,如果找到则执行操作,否则在 iframe 内搜索 webelement 并执行所需操作

Selenium 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 中可用。

但要求是首先在主窗口中搜索,然后仅导航到 iframe。如何处理这样的用例?

有什么建议会有帮助吗?谢谢。

最佳答案

是的,如果主窗口中不存在该元素,您可以编写一个循环来遍历所有 iframe。Java 实现:

 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()

关于java - 有没有办法先在主窗口上搜索 webelement,如果找不到,然后开始在 iframe 内搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55536851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com