【问题标题】:Selenium: How to paste URL onto a new tab - JavaSelenium:如何将 URL 粘贴到新选项卡上 - Java
【发布时间】:2020-11-24 19:53:07
【问题描述】:

我正在努力想办法将文本/网址粘贴到 Chrome 中的新标签上。我在无头模式下在 Linux 上运行我的测试。 因此,我能够启动一个新选项卡,但无法将 URL 粘贴到导航栏上。

为什么我要粘贴 URL?我必须点击一个按钮,它会给我 URL,我必须在新标签页上启动 URL。

这是我试图让它工作的代码。

    copyBtn.click(); //copying the URL
    ((JavascriptExecutor) driver).executeScript("window.open()");// launching a new tab
    SeleniumUtils.switchBrowserTab(driver, 1);
    Actions actions = new Actions(driver);
    actions.sendKeys(Keys.COMMAND, "v").sendKeys(Keys.ENTER).build().perform(); //sending the paste command 
    System.out.println(driver.getCurrentUrl());
    

系统输出正在打印 about:blank 而不是粘贴的文本。我认为这是因为我没有专注于导航栏。我准备了很多博客,但似乎没有办法专注于导航栏。 有人可以说明如何实现这个用例吗?

另外,我手边没有 URL,老实说,我不确定如何获取复制的 URL。因为我不在本地运行,所以我不能使用 ToolKit。 谢谢。

【问题讨论】:

  • 如果你有网址,那么如何:用"window.open(" + url + ")"替换"window.open()"
  • 我手边没有 URL,点击按钮会复制 URL。我不确定如何找回它。另外,copyBtn.getText() 没有给我复制的 URL。
  • 尝试使用java剪贴板库

标签: java selenium selenium-webdriver ui-automation


【解决方案1】:

这个我用了很多:

public void openNewTab(WebDriver driver) throws InterruptedException {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("window.open('');");
    Thread.sleep(100);
}

public void gotoTab(WebDriver driver, int tabIndex) throws InterruptedException {
    List<String> winHandles = new ArrayList<>(driver.getWindowHandles());
    Thread.sleep(500);
    driver.switchTo().window(winHandles.get(tabIndex));
}

WebDriver driver = ...;
openNewTab(driver);
gotoTab(driver, 1); // zero based
driver.get("...");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-18
    • 2010-09-08
    • 2018-08-06
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多