滚动到页面底部并检查是否在末尾Selenium C#

j2qf4p5b  于 2023-10-19  发布在  C#
关注(0)|答案(2)|浏览(204)

所以我很困惑为什么这个代码不工作。
这就是这个代码的作用...
1.使用向下键向下滚动;
1.在向下滚动之前捕获页面高度;
1.检查旧高度是否等于新高度;
1.向下滚动后设置旧高度;
1.如果滚动前后页面高度相同,则返回true并停止滚动;

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
var reachedEnd = false;
var newHeight = js.ExecuteScript("return document.body.scrollHeight");
var oldHeight = js.ExecuteScript("return document.body.scrollHeight");

    while (!reachedEnd)
    {
        driver.FindElement(By.CssSelector("body")).SendKeys(Keys.End);
        Thread.Sleep(2);
        newHeight = js.ExecuteScript("return document.body.scrollHeight");

        if (oldHeight == newHeight)
        {
            reachedEnd = true;
        }
        else
        {
            oldHeight = newHeight;
        }
    }

所以问题是新旧高度在页面末尾相等,但它没有返回true。
对此有什么想法吗?我已经想了三个小时了。

eyh26e7m

eyh26e7m1#

要向下滚动到页面的末尾,您可以使用以下命令:

IJavaScriptExecutor js = (IJavaScriptExecutor) driver;
js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight)");
cnwbcb6i

cnwbcb6i2#

你的方法对我有效,谢谢。这修复了退出循环:

var reachedEnd = false;
var newHeight = (long)js.ExecuteScript("return  document.getElementById('liveFrame').scrollHeight");
var oldHeight = (long)js.ExecuteScript("return document.getElementById('liveFrame').scrollHeight");

screens.Add(new ContentFile(GetUrlScreenshot(left, top, width, height)));
while (!reachedEnd)
{
    driver.FindElement(By.Id("liveFrame")).SendKeys(Keys.PageDown);

    Thread.Sleep(1000);
    screens.Add(new ContentFile(GetUrlScreenshot(left, top, width,    height)));

    newHeight = (long)js.ExecuteScript("return document.getElementById('liveFrame').scrollHeight");
    if (oldHeight == newHeight)
    {
       reachedEnd = true;
    }
    else
    {
        oldHeight = newHeight;
    }
}

问题是在铸造长。

相关问题