【发布时间】:2022-02-19 06:12:46
【问题描述】:
我有一个页面我正在测试练习,在该页面中我有一个链接,我需要单击并导航到然后滚动到新页面上的特定元素。当测试运行时,一切都通过了,但页面没有滚动到有问题的元素。有人可以解释一下吗?
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.Iterator;
import java.util.Set;
public class AspirationBase {
public WebDriver driver;
public JavascriptExecutor js;
public WebElement element;
public String URL = "https://www.aspiration.com";
public String xpath;
public String handleWindow;
public Set<String> allWindows;
public Iterator<String> iterator;
public int sleepTime = 2000;
public AspirationBase(WebDriver driver) {
this.driver = driver;
}
public void launchAspiration() throws InterruptedException {
driver.get(URL);
Thread.sleep(sleepTime);
}
}
package searchaspiration;
import aspirationbase.AspirationBase;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
public class SearchAspiration extends AspirationBase {
public SearchAspiration(WebDriver driver) {
super(driver);
}
public void viewProducts() throws InterruptedException {
handleWindow = driver.getWindowHandle();
xpath = "//*[@id=\"__next\"]/div/header/ul[1]/li[1]/a";
driver.findElement(By.xpath(xpath)).click();
Thread.sleep(sleepTime);
allWindows = driver.getWindowHandles();
iterator = allWindows.iterator();
while (iterator.hasNext()) {
String newURL = iterator.next();
if (!handleWindow.equalsIgnoreCase(newURL)) {
driver.switchTo().window(newURL);
xpath = "//*[@id=\"__next\"]/div/section[7]/div/div[1]/div[1]";
element.findElement(By.xpath(xpath));
(js = (JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element);
}
}
}
}
编辑:在给定代码之前,我尝试简单地导航到链接并滚动到元素,但 selenium 无法识别给定的定位器,因为它试图在打开的原始页面中找到它。现在它似乎只是在运行前几个测试后忽略了我的 while 循环。我更想找到一个关于我哪里出错的解释,而不是一个直接的答案,以便更好地理解
Edit1:在阅读了更多文档后,我意识到问题在于 while 循环中的所有内容都试图找到一个我不想要的已经打开的窗口。我想要完成的是单击第一页中的链接,该链接指向一个新页面,然后将新页面向下滚动到给定元素。如前所述,简单地使用 .click() 导航,然后在新页面上使用元素 xpath 不起作用,因为它试图在前一页上找到 xpath。关于如何识别 xpath 的任何建议都会很棒。这是没有 while 循环的:
import aspirationbase.AspirationBase;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
public class SearchAspiration extends AspirationBase {
public SearchAspiration(WebDriver driver) {
super(driver);
}
public void viewProducts() throws InterruptedException {
xpath = "//*[@id=\"__next\"]/div/header/ul[1]/li[1]/a";
driver.findElement(By.xpath(xpath)).click();
Thread.sleep(sleepTime);
xpath = "//*[@id=\"__next\"]/div/section[7]/div/div[1]";
element.findElement(By.xpath(xpath));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(sleepTime);
}
}
【问题讨论】:
-
这里列出的方法是否适用于您的问题? stackoverflow.com/questions/3401343/…
-
@kpie 是的。我在上面给出的代码之前尝试了类似的东西,但是由于 selenium 没有注册它在新页面上,它无法找到我使用的任何定位器。因此它会尝试在最初打开的页面上找到给定的定位器,而不是链接将用户带到的页面
标签: java selenium selenium-webdriver scroll