gpt4 book ai didi

java - 如何使用 Actions 类在 chrome 中打开新选项卡

转载 作者:行者123 更新时间:2023-11-30 06:32:31 25 4
gpt4 key购买 nike

如何在 Chrome 上打开新标签页。我需要从中获取一些数据,返回到之前的选项卡并输入数据。我知道如何遍历选项卡,但无法打开新选项卡。

Selenium 版本:3.5.2
Chrome 版本:60

package Amazon;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class VerifyAmazonSignInPage {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C://Selenium jars/chromedriver.exe");

WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://www.amazon.in");
driver.findElement(By.xpath("//span[text()='Hello. Sign in']")).click();
driver.findElement(By.id("ap_email")).sendKeys("seleniumoar1234@gmail.com");
driver.findElement(By.id("ap_password")).sendKeys("*****");
driver.findElement(By.id("signInSubmit")).click();
Actions act = new Actions(driver);
act.keyDown(Keys.CONTROL).sendKeys("t").keyUp(Keys.CONTROL).build().perform();
driver.get("http://www.gmail.com");


}

}

最佳答案

我用于 Action class 的经验法则也就是说,仅使用它来模仿最终用户的鼠标操作。请勿将其用于其他目的。

在您的情况下,您需要将 key 发送到浏览器,您可以使用 WebDriver 接口(interface)的任何实现来做到这一点。那么您喜欢如何打开新标签页呢?

最简单的方法是在 body 元素上发送键以打开新选项卡 -

   driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL + "t");

但在某些情况下,这不起作用,所以我更喜欢 JavascriptExecutor ,我写了post因为它是与平台无关的解决方案。

  ((JavascriptExecutor) driver).executeScript("window.open('http://gmail.com/','_blank');");

请注意,打开新选项卡后,您必须处理 switching tab,它不会自动工作。

关于java - 如何使用 Actions 类在 chrome 中打开新选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45812158/

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