gpt4 book ai didi

java - 无法单击元素并重定向到 Selenium 中的新选项卡

转载 作者:行者123 更新时间:2023-12-02 02:24:14 24 4
gpt4 key购买 nike

我正在尝试通过在不同的网站上测试它们来学习 Selenium 。在此过程中,我正在尝试与 Flipkart 网站合作。在此,我想为 puma 提供搜索栏并尝试单击结果项目之一。但我无法使用下面提到的代码来做到这一点。谁能帮忙解决一下吗?

其次,如果我们单击任何项​​目,它将被重定向到新选项卡。如何使用相同的脚本访问新选项卡元素?

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;


public class AutomationTesting {
public static void main(String[] args) {

System.setProperty("webdriver.gecko.driver","/Users/xxxx/eclipse-workspace/seleniumTesting/lib/geckoDriver/geckodriver");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.de");
driver.findElement(By.id("lst-ib")).sendKeys("flipkart");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Flipkart")));
driver.findElement(By.partialLinkText("Flipkart")).click();
driver.findElement(By.cssSelector("._3Njdz7 [class = '_2AkmmA _29YdH8']")).click();
driver.findElement(By.xpath("//input[@class = 'LM6RPg']")).click();
driver.findElement(By.xpath("//input[@class = 'LM6RPg']")).sendKeys("Puma");
driver.findElement(By.xpath("//button[@class = 'vh79eN']")).click();
driver.findElement(By.xpath("//a[@title='Puma Men Black Wallet' and @class= '_1Nyybr _30XEf0']")).click();
}

}

最佳答案

您需要使用窗口 switchTo 功能。

String mainWindowHandle = driver.getWindowHandle();
ArrayList<String> wins = driver.getWindowHandles();
// You can use a for loop here, or get the assumed second window directly
driver.switchTo().window(wins.get(1));
// Test some things, then switch back
driver.close();
driver.switchTo().window(mainWindowHandle);

参见http://www.seleniumhq.org/docs/03_webdriver.jsp#moving-between-windows-and-frames

关于java - 无法单击元素并重定向到 Selenium 中的新选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48029465/

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