如何使用selenium webdriver在滚动中搜索动态加载网格中的元素?

Grid有一个名为Username(具有不同的值)的1000行。

并且网格每个视图只显示20行,其他行仅在滚动时加载 (ajax)。

那么,如何在网格中搜索特定的用户名,因为我们只有滚动时加载的元素。

Scrollintoview方法有帮助吗? 或者我需要使用window.scrollby()直到找到搜索到的项目?

首先,我道歉,因为我以前从未在网格上工作过。 我认为这将是一个框架,将更容易切换,然后使用JavascriptExecutor滚动到元素。 可惜! 网格不是这种情况。
并且,当涉及网格时必须有一个表格。

现在,这对我有用。

  • 首先单击网格上的任何可见元素以使其成为焦点。
  • 然后使用“Keys.PAGE_DOWN”使用网格定位器(xpath,id等)滚动网格,直到找到要查找的元素。
  • 如果在每个卷轴上找不到该元素,则处理该exception会引发并再次滚动。
  • 注意:每次滚动后都不要忘记给一些睡​​眠时间。

    我已经自动化了一个样本网格,并附上了下面的示例工作代码。 希望这有助于解决问题:

     import java.io.IOException; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class ScrollGrid{ public static void main(String[] args) throws IOException, InterruptedException{ WebDriver driver = new FirefoxDriver(); driver.get("https://demos.devexpress.com/ASPxGridViewDemos/PagingAndScrolling/VirtualPaging.aspx"); driver.manage().window().maximize(); //Clicking on an element inside grid to get it into focus driver.findElement(By.xpath("//*[@id='ContentHolder_ASPxGridView1_DXMainTable']//td[.='9/30/1994']")).click(); WebElement ele=null; int flag=0; int count=0; do{ try{ //element to search for while scrolling in grid ele = driver.findElement(By.xpath("//*[@id='ContentHolder_ASPxGridView1_DXMainTable']//td[.='3/28/1996']")); flag=1; } catch(Throwable e){ //scrolling the grid using the grid's xpath driver.findElement(By.xpath("//*[@id='ContentHolder_ASPxGridView1']//div[2]")).sendKeys(Keys.PAGE_DOWN); Thread.sleep(3000); } }while((flag==0) || ((++count)==250)); if(flag==1){ System.out.println("Element has been found.!!"); }else{ System.out.println("Element has not been found.!!"); } highlightElement(driver, ele); //For highlighting the element Thread.sleep(5000L); //to check if the element scrolled to is highlighted. driver.close(); } //For highlighting the element to be located after scroll public static void highlightElement(WebDriver driver, WebElement ele) { try { for (int i = 0; i < 3; i++) { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].setAttribute('style', arguments[1]);",ele, "color: red; border: 2px solid red;"); } } catch(Throwable t) { System.err.println("Error came : " +t.getMessage()); } } } 

    注意:现在可正常工作。 如果找到元素,或者如果在250个滚动后找不到它,它将退出循环。 '250'是相对数字。 您可以将其更改为要在网格上执行的滚动数。

    任何一天我都会选择“ScrollintoView”。
    它将同时滚动并检查元素,并在视图中有元素时停止
    有关代码的帮助,请点击此链接