【问题标题】:c# Selenium IJavaScriptExecutor scrolling down does not workingc# Selenium IJavaScriptExecutor 向下滚动不起作用
【发布时间】:2018-10-22 11:31:55
【问题描述】:

我遇到了问题,因为我需要向下滚动页面, 所以我决定使用IJavaScriptExecutor

IJavaScriptExecutor js =  (IJavaScriptExecutor) driver;
js.executeScript("window.scrollBy(0,1000)"); 

我也试过

js.ExecuteScript("arguments[0].scrollIntoView();", invite); 

js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight)");

但它不起作用。

【问题讨论】:

  • 有什么问题?当你尝试它时发生了什么?
  • 什么也没发生。 IJavaScriptExecutor 被程序简单地忽略了。这就是问题

标签: c# selenium selenium-webdriver webdriver


【解决方案1】:

在尝试向下滚动页面之前,请确保 DOM Tree 已完全呈现。 在这里可以找到详细讨论How can I make sure if some HTML elements are loaded for Selenium + Python?

页面加载完成后,您可以调用scroll() 方法,如下所示:

  • 向下滚动 250 像素:

    IJavaScriptExecutor js = (IJavaScriptExecutor) driver;
    js.ExecuteScript("window.scrollBy(0,250)", "");
    
  • 向下滚动整个页面:

    IJavaScriptExecutor js = (IJavaScriptExecutor) driver;
    js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight)");
    
  • 将元素滚动到视图中:

    IWebElement element = new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("css_element")));
    IJavaScriptExecutor js = (IJavaScriptExecutor) driver;
    js.ExecuteScript("arguments[0].scrollIntoView(true);",element);
    

【讨论】:

  • 所以,我需要创建一个方法,例如等待 30 秒以使网站头部的一部分可见,然后调用 scroll() 方法?对吗?
  • @MariuszBudzisz 你不需要一个函数,只需要一个简单的 WebDriverWait 实例。就可以了。
  • public void Invite(){ var span = new TimeSpan(0, 0, 0, 60, 0); var wait = new WebDriverWait(驱动程序,跨度); wait.Until(foo => foo.FindElement(By.CssSelector("#seo_h1_tag > a:nth-child(1)")).Enabled); js.ExecuteScript("window.scrollBy(0,250)", ""); wait.Until(foo => foo.FindElement(By.CssSelector("button._42ft._4jy0.FriendRequestAdd.addButton._4jy3._517h._51sy")).Enabled); IWebElement 邀请 = driver.FindElement(By.CssSelector("button._42ft._4jy0.FriendRequestAdd.addButton._4jy3._517h._51sy"));邀请.提交();邀请.SendKeys(Keys.Return); } 不工作。
  • @MariuszBudzisz 我不知道("#seo_h1_tag > a:nth-child(1)")。您尝试自动化的确切手动步骤是什么?
  • 1-> 前往 Yagiellonian University facebook fanpage facebook.com/jagiellonian.university ("#seo_h1_tag > a:nth-child(1)") 是 UJ 的 logo,放置在 fanpage 2->向下滚动(不起作用) 3-> 多次按下“添加朋友”按钮
【解决方案2】:

我已经在另一个帖子中发布了解决方案。

问题How to scroll smoothly with Selenium WebDriver and/or Sikuli in Java

回答https://stackoverflow.com/a/51870388/6220192

【讨论】:

    猜你喜欢
    • 2020-03-09
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 2017-11-06
    • 2016-05-30
    相关资源
    最近更新 更多