【问题标题】:Selenium 'Element cannot be scrolled into view' after scrolling element into view with JavaScript使用 JavaScript 将元素滚动到视图后,Selenium '元素无法滚动到视图中'
【发布时间】:2018-10-12 15:09:00
【问题描述】:

我正在通过 JavaScript 将元素滚动到视图中,但是当尝试单击该元素时,会引发异常,表示该元素无法滚动到视图中。当我查看浏览器时,它已成功滚动到视图中。

wait = new WebDriverWait(driver, TimeSpan.FromSeconds(WaitTimeout));
var nextPageButton = wait.Until(ExpectedConditions.ElementToBeClickable(NextPageButtonSelector));
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", nextPageButton);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.width = '100%';", nextPageButton);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.height = '100%';", nextPageButton);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.position = 'fixed';", nextPageButton);
nextPageButton.Click();

附: javascript element.click() 或 Actions 类都不起作用。

【问题讨论】:

  • 先向下滚动,然后等待可点击
  • @Infern0 我刚刚尝试了您的想法,但没有成功。在 wait.Until 调用之前滚动到视图时出现同样的异常。

标签: c# selenium


【解决方案1】:

通过在单击之前添加 Thread.Sleep 调用解决了我自己的问题。我知道不推荐这样做,但它确实是我能找到的唯一解决方案。 :(

wait = new WebDriverWait(driver, TimeSpan.FromSeconds(WaitTimeout));
var nextPageButton = wait.Until(ExpectedConditions.ElementToBeClickable(NextPageButtonSelector));
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", nextPageButton);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.width = '100%';", nextPageButton);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.height = '100%';", nextPageButton);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.position = 'fixed';", nextPageButton);
Thread.Sleep(500);
nextPageButton.Click();

【讨论】:

  • 为什么要在 e2e 测试中处理 css 样式?这可不是好习惯!用户不会那样做——我猜。
  • @nilsK 我正在为公共代理列表抓取第三方网站。有时,下一页按钮会被其他元素稍微遮挡。 (我可以在浏览器中手动轻松点击,但 Selenium 会通过最轻微的难以察觉的重叠来匹配)更改 CSS 修复了该问题。
猜你喜欢
  • 2018-08-09
  • 2016-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多