gpt4 book ai didi

java - 使用 Selenium JAVA 下载在新窗口中打开的 PDF

转载 作者:行者123 更新时间:2023-12-01 19:10:38 45 4
gpt4 key购买 nike

Stackoverflow 中提出了许多与此类似的问题。但这是不同的我现在正在自动化一个网络应用程序,在应用程序结束时,将生成 PDF(它将显示为链接,单击它 PDF 将在新窗口中打开)。我现在正在使用 AUTOIT 来自动化“另存为”对话框。有没有其他方法可以不使用 AutoIT 来下载。

我尝试从标签下的应用程序中的链接获取PDF URL,但它实际上是调用JS在新窗口中打开PDF在新窗口中,PDF实际上位于嵌入标签中,其中src是关于::空白我获取了 PDF 完整的 src,但是当我在没有清除任何 cookie 的情况下使用该 URL 时,我无法获取 PDF

对于这个问题有什么建议吗?

最佳答案

使用ROBOT类上传文件

public String imagePath = System.getProperty("user.dir") +"\\src\\test\\java\\filepath.pdf";

public void uploadFileWithRobot(String imagePath) {
StringSelection stringSelection = new StringSelection(imagePath);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);

Robot robot = null;

try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}

robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(150);
robot.keyRelease(KeyEvent.VK_ENTER);
}

现在单击 PDF 并在新窗口中打开,然后验证 PDF 中是否存在文本

public String readPDFInURL(String text) throws EmptyFileException, IOException {
System.out.println("Enters into READ PDF");
String output = "";
URL url = new URL(driver.getCurrentUrl());
System.out.println("url : " + url);
InputStream is = url.openStream();
BufferedInputStream fileToParse = new BufferedInputStream(is);
PDDocument document = null;
try {
document = PDDocument.load(fileToParse);
output = new PDFTextStripper().getText(document);
if (output.contains(text)) {
System.out.println("Element is matched in PDF is : " + text);
test.log(LogStatus.INFO, "Element is displayed in PDF " + text);
} else {
System.out.println("Element is not matched in PDF");
test.log(LogStatus.ERROR, "Element is not displayed in PDF :: " + text);
throw new AssertionError("Element is not displayed" + text);
}
} finally {
if (document != null) {
document.close();
}
fileToParse.close();
is.close();
}
return output;
}

关于java - 使用 Selenium JAVA 下载在新窗口中打开的 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59486211/

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