#1 楼
链接到我的博客,我将在此进行更详细的讨论。这里的不一致之处是,您是否将Selenium IDE或WebDriver与Java一起使用? Selenium IDE(如您在帖子中所述)可以尝试使用:
/*
* Copyright (c) 2010-2012 Lazery Attack - http://www.lazeryattack.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lazerycode.selenium.filedownloader;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Set;
public class FileDownloader {
private static final Logger LOG = Logger.getLogger(FileDownloader.class);
private WebDriver driver;
private String localDownloadPath = System.getProperty("java.io.tmpdir");
private boolean followRedirects = true;
private int httpStatusOfLastDownloadAttempt;
public FileDownloader(WebDriver driverObject) {
this.driver = driverObject;
}
/**
* Specify if the FileDownloader class should follow redirects when trying to download a file
*
* @param value
*/
public void followRedirectsWhenDownloading(boolean value) {
this.followRedirects = value;
}
/**
* Get the current location that files will be downloaded to.
*
* @return The filepath that the file will be downloaded to.
*/
public String localDownloadPath() {
return this.localDownloadPath;
}
/**
* Set the path that files will be downloaded to.
*
* @param filePath The filepath that the file will be downloaded to.
*/
public void localDownloadPath(String filePath) {
this.localDownloadPath = filePath;
}
/**
* Download the file specified in the href attribute of a WebElement
*
* @param element
* @return
* @throws Exception
*/
public String downloadFile(WebElement element) throws Exception {
return downloader(element, "href");
}
/**
* Download the image specified in the src attribute of a WebElement
*
* @param element
* @return
* @throws Exception
*/
public String downloadImage(WebElement element) throws Exception {
return downloader(element, "src");
}
/**
* Gets the HTTP status code of the last download file attempt
*
* @return
*/
public int httpStatusOfLastDownloadAttempt() {
return this.httpStatusOfLastDownloadAttempt;
}
/**
* Load in all the cookies WebDriver currently knows about so that we can mimic the browser cookie state
*
* @param seleniumCookieSet
* @return
*/
private HttpState mimicCookieState(Set<org.openqa.selenium.Cookie> seleniumCookieSet) {
HttpState mimicWebDriverCookieState = new HttpState();
for (org.openqa.selenium.Cookie seleniumCookie : seleniumCookieSet) {
Cookie httpClientCookie = new Cookie(seleniumCookie.getDomain(), seleniumCookie.getName(), seleniumCookie.getValue(), seleniumCookie.getPath(), seleniumCookie.getExpiry(), seleniumCookie.isSecure());
mimicWebDriverCookieState.addCookie(httpClientCookie);
}
return mimicWebDriverCookieState;
}
/**
* Set the host configuration based upon the URL of the file/image that will be downloaded
*
* @param hostURL
* @param hostPort
* @return
*/
private HostConfiguration setHostDetails(String hostURL, int hostPort) {
HostConfiguration hostConfig = new HostConfiguration();
hostConfig.setHost(hostURL, hostPort);
return hostConfig;
}
/**
* Perform the file/image download.
*
* @param element
* @param attribute
* @return
* @throws IOException
* @throws NullPointerException
*/
private String downloader(WebElement element, String attribute) throws IOException, NullPointerException {
String fileToDownloadLocation = element.getAttribute(attribute);
if (fileToDownloadLocation.trim().equals("")) throw new NullPointerException("The element you have specified does not link to anything!");
URL fileToDownload = new URL(fileToDownloadLocation);
File downloadedFile = new File(this.localDownloadPath + fileToDownload.getFile().replaceFirst("/|\\", ""));
if (downloadedFile.canWrite() == false) downloadedFile.setWritable(true);
HttpClient client = new HttpClient();
client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
client.setHostConfiguration(setHostDetails(fileToDownload.getHost(), fileToDownload.getPort()));
client.setState(mimicCookieState(this.driver.manage().getCookies()));
HttpMethod getFileRequest = new GetMethod(fileToDownload.getPath());
getFileRequest.setFollowRedirects(this.followRedirects);
LOG.info("Follow redirects when downloading: " + this.followRedirects);
LOG.info("Sending GET request for: " + fileToDownload.toExternalForm());
this.httpStatusOfLastDownloadAttempt = client.executeMethod(getFileRequest);
LOG.info("HTTP GET request status: " + this.httpStatusOfLastDownloadAttempt);
LOG.info("Downloading file: " + downloadedFile.getName());
FileUtils.copyInputStreamToFile(getFileRequest.getResponseBodyAsStream(), downloadedFile);
getFileRequest.releaseConnection();
String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
LOG.info("File downloaded to '" + downloadedFileAbsolutePath + "'");
return downloadedFileAbsolutePath;
}
}
它很容易使用,您只需要提供Image / Hyperlink的WebElement。您想要下载的内容,因此与其尝试在WebElement上单击,还不如将其传递给FileDownloader对象: Java,因此跨浏览器/平台兼容。
Github上的代码
#2 楼
我通常将键盘快捷方式与Java中的Robot类一起使用,以模拟手动执行的操作。在IE 8中,保存文件将分三个步骤:1) Click link or Press Enter key on the link.
2) type S.
3) Hit Enter.
我首先手动为第一个测试用例执行相同的操作。下载完成后,将其保存在某个文件夹中,清理该文件夹,然后单击复选框以关闭此对话框。
接下来,我使用以下代码:
WebElement link = driver.findElement(By.xpath("myxpath"));
clickAndSaveFileIE(link);
public static void clickAndSaveFileIE(WebElement element) throws InterruptedException{
try {
Robot robot = new Robot();
//get the focus on the element..don't use click since it stalls the driver
element.sendKeys("");
//simulate pressing enter
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
//wait for the modal dialog to open
Thread.sleep(2000);
//press s key to save
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
Thread.sleep(2000);
//press enter to save the file with default name and in default location
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (AWTException e) {
e.printStackTrace();
}
评论
由于无法使用AutoIt,因此在支持Linux环境中的自动化问题时,可以使用机械手类
– Rakesh Prabhakaran
2012年7月31日在12:17
#3 楼
处理任何对话框的技巧是使用诸如AutoIT之类的外部工具来处理“上载”对话框,“下载”对话框和“ NTLM身份验证”对话框。请注意,此解决方案仅适用于在Windows环境中执行脚本的用户。使用AutoIT,您可以编写一个简单的脚本来保存“保存”对话框,然后可以将该脚本转换为可执行文件。具有命令行参数的程序可以随时从程序中调用它。
执行以下步骤可以解决您的问题。
下载autoIT工具。
保存将以下提到的脚本添加到系统中的
save_dialog.au3
文件中。从AutoIT安装目录中打开“
Compile Script to .exe
”程序。 。 (请说save_dialog.au3
)如果您使用Java编写自动化代码,请在单击“下载链接”或希望出现下载对话框之前使用下面的代码行。
String[] dialog = new String[]{ "C:\save_ie_file.exe","Save to...","Save", "C:\selenium_downloads\" }; // path to exe, dialog title, save/cancel/run, path to save file.
Process pp1 = Runtime.getRuntime().exec(dialog); // run the executable to wait for download link and process
selenium.click("id=download_link"); // code to click on download link
pp1.destroy(); // kill the process looking to download
save_dialog.au3代码从这里被公然复制免责声明...我不是该答案中指出的博客作者:
AutoItSetOption("WinTitleMatchMode","2") ; set the select mode to select using substring
if $CmdLine[0] < 2 then
; Arguments are not enough
msgbox(0,"Error","Supply all the arguments, Dialog title,Run/Save/Cancel and Path to save(optional)")
Exit
EndIf
; wait Until dialog box appears
WinWait($CmdLine[1]) ; match the window with substring
$title = WinGetTitle($CmdLine[1]) ; retrives whole window title
WinActivate($title)
If (StringCompare($CmdLine[2],"Run",0) = 0) Then
WinActivate($title)
ControlClick($title,"","Button1")
EndIf
If (StringCompare($CmdLine[2],"Save",0) = 0) Then
WinWaitActive($title)
ControlClick($title,"","Button2")
; Wait for the new dialogbox to open
Sleep(2)
WinWait("Save")
$title = WinGetTitle("Save")
;$title = WinGetTitle("[active]")
if($CmdLine[0] = 2) Then
;click on the save button
WinWaitActive($title)
ControlClick($title,"","Button2")
Else
;Set path and save file
WinWaitActive($title)
ControlSetText($title,"","Edit1",$CmdLine[3])
ControlClick($title,"","Button2")
EndIf
EndIf
If (StringCompare($CmdLine[2],"Cancel",0) = 0) Then
WinWaitActive($title)
ControlClick($title,"","Button3")
EndIf
#4 楼
我没有使用上面的代码,而是使用下面的代码,它们显示了如果我们同时按下“ Alt + S”按钮,然后Internet Explorer浏览器将保存下载的文件,但是重要的是我们不能在这里使用单击按钮方法,因为光标可能会卡在该按钮,因此记住它非常重要,我们必须在此处使用“发送键”方法来单击按钮。WebElement link = driver.findElement(By.xpath("myxpath"));
clickAndSaveFileIE(link);
public static void clickAndSaveFileIE(WebElement element) throws InterruptedException{
try {
Robot robot = new Robot();
//get the focus on the element..don't use click since it stalls the driver
element.sendKeys("");
//simulate pressing enter
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
//wait for the modal dialog to open
Thread.sleep(2000);
//press s key to save
robot.keyPress(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_ALT);
Thread.sleep(2000);
//press enter to save the file with default name and in default location
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
} catch (AWTException e) {
e.printStackTrace();
}
评论
WebElement链接= driver.findElement(By.xpath(“ myxpath”));在上面的代码行中,您要为myxpath传递哪个xpath?