是的,如果主窗口中不存在该元素,则可以编写一个循环遍历所有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 firstdriver.switch_to.default_content()# check if the elment present in the parent windowif (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()