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

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

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

  1. IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
  2. var reachedEnd = false;
  3. var newHeight = js.ExecuteScript("return document.body.scrollHeight");
  4. var oldHeight = js.ExecuteScript("return document.body.scrollHeight");
  5. while (!reachedEnd)
  6. {
  7. driver.FindElement(By.CssSelector("body")).SendKeys(Keys.End);
  8. Thread.Sleep(2);
  9. newHeight = js.ExecuteScript("return document.body.scrollHeight");
  10. if (oldHeight == newHeight)
  11. {
  12. reachedEnd = true;
  13. }
  14. else
  15. {
  16. oldHeight = newHeight;
  17. }
  18. }

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

eyh26e7m

eyh26e7m1#

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

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

cnwbcb6i2#

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

  1. var reachedEnd = false;
  2. var newHeight = (long)js.ExecuteScript("return document.getElementById('liveFrame').scrollHeight");
  3. var oldHeight = (long)js.ExecuteScript("return document.getElementById('liveFrame').scrollHeight");
  4. screens.Add(new ContentFile(GetUrlScreenshot(left, top, width, height)));
  5. while (!reachedEnd)
  6. {
  7. driver.FindElement(By.Id("liveFrame")).SendKeys(Keys.PageDown);
  8. Thread.Sleep(1000);
  9. screens.Add(new ContentFile(GetUrlScreenshot(left, top, width, height)));
  10. newHeight = (long)js.ExecuteScript("return document.getElementById('liveFrame').scrollHeight");
  11. if (oldHeight == newHeight)
  12. {
  13. reachedEnd = true;
  14. }
  15. else
  16. {
  17. oldHeight = newHeight;
  18. }
  19. }

问题是在铸造长。

展开查看全部

相关问题