首先,我道歉,因为我以前从未在网格上工作过.我认为这将是一个框架,将更容易切换,然后使用JavascriptExecutor滚动到元素.可惜!网格不是这种情况.并且,当涉及网格时必须有一个表格.
原文链接:https://www.f2er.com/ajax/160163.html现在,这对我有用.
>首先单击网格上的任何可见元素以使其成为焦点.
>然后使用’keys.PAGE_DOWN’使用网格定位器(xpath,id等)滚动网格,直到找到您要查找的元素.
>如果在每个卷轴上找不到元素,则处理异常会引发并再次滚动.
注意:每次滚动后都不要忘记给一些睡眠时间.
我已经自动化了一个样本网格,并附上了下面的示例工作代码.希望这有助于解决问题:
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’是相对数字.您可以将其更改为要在网格上执行的滚动数.