Selenium 代码在延迟加载的 Web 元素中水平滚动

Ami*_*mit 2 java selenium

有人可以帮我编写一段 selenium 代码,通过在延迟加载时水平滚动来查找 div 内的元素吗?

例如,在以下 URL 中,我们向右滚动后会加载元素:

  1. http://ressio.github.io/lazy-load-xt/demo/horizo​​ntal.htm
  2. http://www.appelsiini.net/projects/lazyload/enabled_wide_container.html

我努力了 :

 1. ((JavascriptExecutor) driver).executeScript("window.scrollTo(<x-corodinate>,<y-coordinate>)");
 2. ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", element); 
 3. ((JavascriptExecutor) driver).executeScript("window.scrollBy(<x-corodinate>,<y-coordinate>)");
 4. ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Run Code Online (Sandbox Code Playgroud)

但并没有解决我的目的。

我使用的是 java 1.8 ,selenium jar 版本是 3.0.1 和 Firefox 50.0.2。

File driverPathFirefox = new File("PATH \\TO \\ Driver \\geckodriver.exe");
System.setProperty("webdriver.gecko.driver",driverPathFirefox.getAbsolutePath()); 
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(25000, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.navigate().to(URL);// URL could be the one referred in the question
WebElement scrollArea = driver.findElement(By.xpath(<Xpath of the div>));
// Capturing xpath of div from the URL referred above 
// xpath for div in http://ressio.github.io is "html/body/div[1]/div[2]"
// xpath for div in http://www.appelsiini.net is ".//*[@id='container']"

// Now here I need the code to scroll the web element horizontally 
// until desired element is visible.

driver.quit();
Run Code Online (Sandbox Code Playgroud)

硒依赖项是:

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-api</artifactId>
        <version>3.0.1</version>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

Mos*_*sho 5

尝试其中一个(在您的第一个链接上测试):

WebElement scrollArea = driver.findElement(By.className("wrapper"));

// Scroll to div's most right:
((JavascriptExecutor) driver).executeScript("arguments[0].scrollLeft = arguments[0].offsetWidth", scrollArea);

// Or scroll the div by pixel number:
((JavascriptExecutor) driver).executeScript("arguments[0].scrollLeft += 250", scrollArea);
Run Code Online (Sandbox Code Playgroud)

为了scrollIntoView你需要element存在于 DOM 中,所以也许这就是它不适合你的原因。至于window.scroll您正在尝试滚动窗口而不是在元素内。