1.代码
1 public class SaveImage extends TestCase { 2 private WebDriver driver; 3 private Actions action; 4 private String baseUrl; 5 6 @Before 7 public void setUp() throws Exception { 8 baseUrl = "http://baike.pcbaby.com.cn/recipe/"; 9 System.setProperty("webdriver.chrome.driver", 10 "C:\\Users\\test\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe"); 11 driver = new ChromeDriver(); 12 driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); 13 action = new Actions(driver); 14 } 15 16 @Test 17 public void testDownload() throws Exception { 18 driver.get(baseUrl); 19 WebElement info = new WebDriverWait(driver, 10) 20 .until(ExpectedConditions.presenceOfElementLocated(By.xpath(".//a[2]/em"))); 21 assertEquals("食谱", info.getText()); 22 driver.findElement(By.linkText("1")).click(); 23 WebElement image = driver.findElement(By.xpath(".//*[@class='pic']/a/img")); 24 action.contextClick(image).build().perform(); 25 try { 26 /* 27 * 使用Actions没办法拿到右键菜单 action.sendKeys(Keys.ARROW_DOWN).perform(); 28 * action.sendKeys(Keys.ARROW_DOWN).perform(); 29 * action.sendKeys(Keys.ENTER).perform(); 30 * 使用Java原生键盘操作类Robot 31 */ 32 Robot robot = new Robot(); 33 robot.keyPress(KeyEvent.VK_DOWN); 34 Thread.sleep(1000); 35 robot.keyPress(KeyEvent.VK_DOWN); 36 Thread.sleep(1000); 37 robot.keyPress(KeyEvent.VK_DOWN); 38 Thread.sleep(1000); 39 robot.keyPress(KeyEvent.VK_DOWN); 40 Thread.sleep(1000); 41 robot.keyPress(KeyEvent.VK_DOWN); 42 Thread.sleep(1000); 43 robot.keyPress(KeyEvent.VK_DOWN); 44 Thread.sleep(1000); 45 robot.keyPress(KeyEvent.VK_DOWN); 46 Thread.sleep(1000); 47 48 robot.keyRelease(KeyEvent.VK_DOWN); 49 Thread.sleep(1000); 50 robot.keyPress(KeyEvent.VK_ENTER); 51 } catch (Exception e) { 52 e.printStackTrace(); 53 } 54 55 try { 56 Thread.sleep(2000); 57 } catch (InterruptedException e) { 58 e.printStackTrace(); 59 } 60 try { 61 //使用autoit实现保存 62 Runtime.getRuntime().exec("E:\\storage\\selenium\\download\\test.exe"); 63 //等待保存完成 64 Thread.sleep(10000); 65 } catch (Exception e) { 66 e.printStackTrace(); 67 } 68 69 } 70 71 @After 72 public void tearDown() throws Exception { 73 driver.quit(); 74 } 75 }
2.使用autoit实现保存
使用autoit拖动Finder Tool到需要获取界面信息的输入框及按钮。
3.编写autoit实现保存代码
ControlFocus("另存为", "","Edit1") ;ControlFocus("title","text",controlID) Edit1=Edit instance 1 WinWait("[CLASS:#32770]","",10) $text = ControlGetText("另存为", "","Edit1") $filename = "E:\storage\selenium\download\" + $text Sleep(1000) ControlSetText("另存为", "", "Edit1", $filename) Sleep(5000) ;ControlFocus("另存为", "","Button1") ControlClick("另存为","保存(&S)","Button1")
4.使用autoit的Compile Script to .exe工具将该au3文件转为.exe可执行文件