有一个 Grid,它有 1000 行,其中有一列名为 Username(具有不同的值)。
并且网格每个 View 将仅显示 20 行,其他行将仅在滚动时加载(ajax)。
那么,如何在网格中搜索特定的用户名,因为我们只有滚动加载的元素。
Scrollintoview
方法有帮助吗?或者我是否需要使用 window.scrollby()
直到找到搜索的项目?
最佳答案
首先,我很抱歉,因为我以前从未在网格上工作过。我认为这将是一个框架,使用 JavascriptExecutor 可以更轻松地切换和滚动到该元素。可惜!网格不是这种情况。
而且,涉及网格就必须有表格。
现在,这就是对我有用的方法。
<强>
注意:不要忘记在每次滚动后给一些 sleep 时间。
我已经自动化了一个示例网格,并附上了下面的示例工作代码。希望这有助于找出问题:
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”是一个相对数字。您可以将其更改为您要在网格上执行的滚动次数。
关于java - 如何使用 selenium webdriver 在滚动的动态加载网格中搜索元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26729532/