繁体   English   中英

Selenium - 等待 ScrollIntoView 完成

[英]Selenium - Wait for the ScrollIntoView to finish

我需要滚动到一个元素并截取页面的屏幕截图,但驱动程序在页面完全滚动到该元素之前截取了屏幕截图。 我用这种方式睡了一段时间

driver.execute_script("""arguments[0].scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' });""", element)
time.sleep(1)
scr = driver.get_screenshot_as_png()

但我真的不想使用睡眠,因为它们不是面向测试的。 我试图等待元素可见,但它也不起作用。 另一种尝试是使用 ActionChains 移动到元素,但它没有显示整个元素在其上移动。 有没有办法等待滚动完成? 除了屏幕截图的这种特定情况之外,了解等待滚动完成的方法会很有用。

public static void fullScren(String filename) throws IOException
{

        Screenshot myScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver);
        ImageIO.write(myScreenshot.getImage(),"PNG",new File("src/main/java/ScreenShots/" + filename + ".jpg"));
    }

您必须使用此向下滚动并通过 selenium 拍摄全屏

WebDriverWait(driver,30).until(EC.visibility_of_element_located((By.XPATH,"yourelementslocator")))

使用预期条件的可见性

我找到了一个使用 Javascript 等到元素完全可见的解决方案:

def wait_until_specific_condition(func, timeout=30):
  
    endtime = time.time() + timeout
    while True:
       if time.time() > endtime:
            raise TimeoutException("The condition is not satisfied")
       result = func()
       if result is True:
            return result

所以有了这个 function 我等到满足特定条件; 在我的情况下,条件是使用 Javascript 以这种方式获得的元素的整个可见性:

driver.execute_script("arguments[0].scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' });",
                          element)
is_visible_script = """function isScrolledIntoView(el) {
                                    var rect = el.getBoundingClientRect();
                                    var elemTop = rect.top;
                                    var elemBottom = rect.bottom;
                                
                                    // Only completely visible elements return true:
                                    var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
                                    // Partially visible elements return true:
                                    //isVisible = elemTop < window.innerHeight && elemBottom >= 0;
                                    return isVisible;
                                }
                           return isScrolledIntoView(arguments[0]);"""
wait_until_specific_condition(lambda: driver.execute_script(is_visible_script, element))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM