Is there a way to search webelement on a main window first, if not found, then start searching inside iframes?

后端 未结 1 1101
天涯浪人
天涯浪人 2020-11-30 16:08

Requirement: Bydefault, search for webelement on main window, if found perform action else search for webelement inside iframes and perform required action

Selenium

相关标签:
1条回答
  • 2020-11-30 16:19

    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 Implementation

    # 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()
    
    0 讨论(0)
提交回复
热议问题