gpt4 book ai didi

java - 使用 Selenium WebDriver java 单击动态加载页面的元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:26:18 25 4
gpt4 key购买 nike

我需要点击动态加载页面的特定元素。滚动页面时生成的 Web 元素。它类似于 jabong 网页。

我尝试在 jabong 网页上这样做,这是我的代码

    WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to("http://www.jabong.com/men/clothing/"
+ "?source=topnav");


driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
System.out.println("Close the modal popup");
driver.findElement(By.id("jab-vchr-cls")).click();
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

/**
* while(true) loop is required to search the
* element until element found.We put find
* element within try-catch and if it get
* exception it scroll the page and again
* try to find the element.
*/
while(true) {

((JavascriptExecutor)driver).executeScript("window.scrollBy(0,100)", "");
try {
WebElement element = driver.findElement(By.xpath("//*[@id='http: //static3.jassets.com/p/The-Indian-Garage-Co.-Checks-Red-Casual-Shirt-2889-679124-1-catalog.jpg']/img"));
Wait<WebDriver> wait_element=new WebDriverWait(driver, 10);
wait_element.until(ExpectedConditions.elementToBeClickable(element));
element.click();
System.out.println("!!!!!!!!!!!!!!At Last Get Success!!!!!!!!!!!!!!!!");
break;

}
catch (Exception ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
}
}

}

我的问题是

1.有没有更好的方法来做这件事?

2.如何使这个脚本更快?

最佳答案

如果你想避免 while(true) 你可以这样做,虽然我不认为这个循环有任何问题。

    boolean reachedbottom = Boolean.parseBoolean(js.executeScript("return $(document).height() == ($(window).height() + $(window).scrollTop());").toString());

while (!reachedbottom) {
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,600)", "");
try {
reachedbottom=Boolean.parseBoolean(js.executeScript("return $(document).height() == ($(window).height() + $(window).scrollTop());").toString());
WebElement element = driver.findElement(By.xpath("//*[@id='http://static3.jassets.com/p/The-Indian-Garage-Co.-Checks-Red-Casual-Shirt-2889-679124-1-catalog.jpg']/img"));
Wait<WebDriver> wait_element = new WebDriverWait(driver, 5);
wait_element.until(ExpectedConditions.elementToBeClickable(element));
element.click();
System.out.println("!!!!!!!!!!!!!!At Last Get Success!!!!!!!!!!!!!!!!");
break;
} catch (Exception ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
}
}

关于java - 使用 Selenium WebDriver java 单击动态加载页面的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20955226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com