如何单击href =“ javascript:void(0)”链接并将路径传递到打开的窗口(Selenium)

时间:2018-06-27 20:41:13

标签: java selenium selenium-firefoxdriver

页面上有一个像这样的元素:

<a href="javascript:void(0)"> Computer durchsuchen </a>

如果单击此链接,则会打开一个窗口,您可以在其中选择图像(路径)。我设法单击链接,然后打开了窗口。我的问题是,现在我该如何通过路径以及如何再次将其关闭?

This is the site it concerns...

这是到目前为止我编写的代码:

    WebDriver driver = new FirefoxDriver();

    driver.get("https://www.shirtee.com/de/designer/?id=1140/");
    WebElement link = driver.findElement(By.cssSelector(".upload-image-drop-zone a"));

    Actions ob = new Actions(driver);
    ob.click(link);
    org.openqa.selenium.interactions.Action action  = ob.build();
    action.perform();

Here you can see a screenshot of the processes that happen...

1 个答案:

答案 0 :(得分:0)

由于Selenium无法与本机窗口交互,因此可以使用Robot类:

Robot robot = new Robot();
StringSelection selection = new StringSelection("Absolute path of the file");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection,null);

robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
robot.setAutoDelay(2000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

完整代码如下:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

public class Test  {
  public static void main(String[] args) throws InterruptedException, AWTException {
    final WebDriver driver = new ChromeDriver();

    driver.get("https://www.shirtee.com/de/designer/?id=1140/");

    WebElement link = driver.findElement(By.cssSelector(".upload-image-drop-zone a"));
    link.click();
    Thread.sleep(500); // small pause

    Robot robot = new Robot();
    StringSelection selection = new StringSelection("C:\\full\\path\\to\\file\\image.png");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection,null);

    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyRelease(KeyEvent.VK_V);
    robot.setAutoDelay(2000);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

    Thread.sleep(3000); // only to see the result
    driver.quit();
  }
}

您可以在文档here中找到更多信息。