137.md 12.5 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
# 10克 高级WebDriver –将屏幕截图保存到Word文档

> 原文: [https://javabeginnerstutorial.com/selenium/10g-advanced-webdriver-saving-screenshots-to-word-document/](https://javabeginnerstutorial.com/selenium/10g-advanced-webdriver-saving-screenshots-to-word-document/)

嗨冠军! 希望您度过愉快的时光[截屏并将其保存在本地](https://javabeginnerstutorial.com/selenium/10f-advanced-webdriver-taking-screenshot/)。 今天,让我们看看如何创建Word文档,并将在测试用例中捕获的所有图像插入其中。 每个测试用例都有一个单独的文档,不仅可以帮助我们保持工作空间井井有条,而且搜索特定的屏幕快照也很容易。 最好的部分是,我们将编写代码,以便所有这些事情自动发生而无需任何人工干预。

请允许我直截了当。

## **步骤1:**

下载几个JAR,使我们的工作更加轻松。

**java2word-3.3.jar** -帮助我们创建Word文档并以所需方式对其进行操作。

**xstream-1.3.1.jar** –处理图片

让我们继续从 [https://code.google.com/archive/p/java2word/downloads](https://code.google.com/archive/p/java2word/downloads) (在撰写本文时的下载位置)下载这两个JAR文件。 我还将这些JAR以及本文中处理的所有其他代码文件一起放在我们的 [GitHub存储库](https://github.com/JBTAdmin/Selenium)中。

## **步骤2:**

将这些JAR添加到我们的项目构建路径中。

之前,我们已经多次看到此过程,因此,我不再重复(有关详细说明,请参阅[文章](https://javabeginnerstutorial.com/selenium/9b-webdriver-eclipse-setup/)的步骤3)。

## **步骤3:**

创建一个类“ **SaveDocument.java** ”。

将以下代码添加到类文件中,

```java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

import word.api.interfaces.IDocument;
import word.w2004.Document2004;
import word.w2004.Document2004.Encoding;
import word.w2004.elements.BreakLine;
import word.w2004.elements.Heading1;
import word.w2004.elements.Heading3;
import word.w2004.elements.Image;
import word.w2004.elements.Paragraph;
import word.w2004.style.HeadingStyle.Align;

public class SaveDocument {

  public static void createDoc(String testCaseName, String[] imgFileNames) {
    // Create a document object
    IDocument myDoc = new Document2004();
    myDoc.encoding(Encoding.UTF_8);
    // Inserts one breakline
    myDoc.addEle(BreakLine.times(1).create()); 
    // Add client logo to document header
    myDoc.getHeader().addEle(Image.from_FULL_LOCAL_PATHL("/Selenium/Logo.png")
        .setHeight("30")
        .setWidth("20")
        .getContent());
    // Add Project name to document header
    myDoc.getHeader().addEle(Heading3.with(" ProjectName").withStyle().align(Align.RIGHT).create());
    // Specify Test case name as document heading
        myDoc.addEle(Heading1.with(testCaseName + " Test Case").withStyle().align(Align.CENTER).create());
        myDoc.addEle(BreakLine.times(1).create());
        // Add a description paragraph
        myDoc.addEle(Paragraph
                .with("Following are the related screenshots")
                .create());
        myDoc.addEle(BreakLine.times(1).create());
        // Add company name to document footer
        myDoc.getFooter().addEle(
                Paragraph.with("@CompanyName").create());
        // Loop through all the image files
        for(String file:imgFileNames){
        	// Insert each image file to the document
        	myDoc.addEle(Image.from_FULL_LOCAL_PATHL(
                                "/Selenium/screenshots/" + file + ".png") 
                                .setHeight("350")
                                .setWidth("500")
                                .getContent());
        	// Insert 2 linebreaks at the end of each inserted image
        	myDoc.addEle(BreakLine.times(2).create());
        }
        // Insert an image from web
        myDoc.addEle(Image
                .from_WEB_URL("http://www.google.com/images/logos/ps_logo2.png"));

        // Create the word document specifying a location
        File fileObj = new File("\\Selenium\\" + testCaseName + ".doc");
        PrintWriter writer = null;
        try {
         writer = new PrintWriter(fileObj);
        } catch (FileNotFoundException e) {
         e.printStackTrace();
        }

        String myWord = myDoc.getContent();

        writer.println(myWord);
        writer.close();
        // Print a confirmation image to console
        System.out.println("Word document created successfully!");
       }
}
```

每行都提供了注释,以使代码易于说明。

`public static void createDoc(String testCaseName, String[] imgFileNames)` -此方法有两个参数。 第一个是一个字符串,它指定测试用例的名称。 这将是将要创建的单词文档的名称。 第二个参数是作为该测试用例的一部分捕获的所有屏幕快照名称的数组。

在这种方法中,我们将创建一个文档对象并执行诸如

*   添加标题,段落
*   在标题中添加客户徽标和公司名称
*   在页脚中添加公司名称
*   插入作为特定测试用例一部分捕获的所有屏幕截图
*   从网上插入图片(只是为了证明这种情况也是可行的)
*   将单词文档和测试用例的名称保存在特定位置

## **步骤4:**

对“ **SaveScreenshot.java** ”文件进行了一些修改。

对我们在[先前文章](https://javabeginnerstutorial.com/selenium/10f-advanced-webdriver-taking-screenshot/)中创建的“ SaveScreenshot.java”类进行了一些更改。

1.  删除生成时间戳的函数,并
2.  文件扩展名从“ .jpg”更改为“ .png”

现在的代码看起来像这样,

```java
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public class SaveScreenshot {

  public static void capture(String screenshotName, WebDriver driver) {
    // Cast driver object to TakesScreenshot
    TakesScreenshot screenshot = (TakesScreenshot) driver;
    // Get the screenshot as an image File
    File src = screenshot.getScreenshotAs(OutputType.FILE);
    try {
      // Specify the destination where the image will be saved
      File dest = new File("\\Selenium\\screenshots\\" + screenshotName + ".png");
      // Copy the screenshot to destination
      FileUtils.copyFile(src, dest);
    } catch (IOException ex) {
      System.out.println(ex.getMessage());
    }
  }
}
```

## **示例场景**

1.  打开Firefox浏览器。
2.  导航到Google帐户创建页面
3.  通过ID找到名字文本框
4.  输入“ fname01”作为名字
5.  截取屏幕截图,并将其命名为“ testCaseName” +“ 1”
6.  按名称找到姓氏文本框
7.  输入“ lname01”作为姓氏
8.  截取屏幕截图并将其命名为“ testCaseName” +“ 2”
9.  在指定位置创建一个word文档,并将这两个屏幕截图都插入其中。

### **JUnit代码:**

WordDocWithScreenshotTest.java类

```java
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.blog.utilities.SaveDocument;
import com.blog.utilities.SaveScreenshot;

public class WordDocWithScreenshotTest {
  //Declaring variables
  private WebDriver driver; 
  private String baseUrl;
  private String testCaseName = "WordDocWithScreenshot";

  @Before
  public void setUp() throws Exception{
    // Selenium version 3 beta releases require system property set up
    System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
        + "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
    // Create a new instance for the class FirefoxDriver
    // that implements WebDriver interface
    driver = new FirefoxDriver();
    // Implicit wait for 5 seconds
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    // Assign the URL to be invoked to a String variable
    baseUrl = "https://accounts.google.com/SignUp";
  }

  @Test
  public void testPageTitle() throws Exception{
    // Open baseUrl in Firefox browser window
    driver.get(baseUrl);
    // Locate First Name text box by id and
    // assign it to a variable of type WebElement
    WebElement firstName = driver.findElement(By.id("firstName"));
    // Clear the default placeholder or any value present
    firstName.clear();
    // Enter/type the value to the text box
    firstName.sendKeys("fname01");
    //Take a screenshot
    SaveScreenshot.capture(testCaseName + "1", driver);
    // Locate last name text box by name
    WebElement lastName = driver.findElement(By.name("lastName"));
    // Clear and enter a value
    lastName.clear();
    lastName.sendKeys("lname01");
    // Take a screenshot
    SaveScreenshot.capture(testCaseName + "2", driver);
    // Create a word document and include all screenshots
    SaveDocument.createDoc(testCaseName, new String[]{testCaseName + "1",testCaseName + "2"});
  }

   @After
    public void tearDown() throws Exception{
    // Close the Firefox browser
    driver.close();
  }
}
```

如果遵循注释,该代码是不言自明的。 Eclipse的输出如下,

![Document Eclipse output](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20810%20377'%3E%3C/svg%3E)

<noscript><img alt="Document Eclipse output" class="alignnone size-full wp-image-13504" height="377" src="img/cfe92b1c436c1f2d0946c238a4c772f1.png" width="810"/><p>在Eclipse IDE中,“ JUnit”窗格清楚地显示了测试用例“ <strong> WordDocWithScreenshotTest.java </strong>”已通过,并且控制台没有错误。 按预期打印“ Word文档创建成功”。</p><p>按照代码中的指定,屏幕快照将以上述格式的名称保存到“ <strong> E:/ Selenium / screenshots </strong>”路径中。</p><p><img alt="Saved screenshots" class="alignnone size-full wp-image-13505" data-lazy-src="https://javabeginnerstutorial.com/wp-content/uploads/2018/06/5_WordSavedScreenshots-1.jpg" height="239" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20389%20239'%3E%3C/svg%3E" width="389"/></p><noscript><img alt="Saved screenshots" class="alignnone size-full wp-image-13505" height="239" src="img/5c56b0f1090d7f365f904ce1cb7bc6d6.png" width="389"/><p>还将创建单词文档并将其保存在指定的位置“ <strong> E:/ Selenium / </strong>”中。 该文件如下所示,</p><p><img alt="Created Word Document" class="alignnone size-full wp-image-13503" data-lazy-sizes="(max-width: 1005px) 100vw, 1005px" data-lazy-src="https://javabeginnerstutorial.com/wp-content/uploads/2018/06/6_WordCreatedDoc-1.jpg" data-lazy-srcset="https://javabeginnerstutorial.com/wp-content/uploads/2018/06/6_WordCreatedDoc-1.jpg 1005w, https://javabeginnerstutorial.com/wp-content/uploads/2018/06/6_WordCreatedDoc-1-300x185.jpg 300w, https://javabeginnerstutorial.com/wp-content/uploads/2018/06/6_WordCreatedDoc-1-768x473.jpg 768w" height="619" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%201005%20619'%3E%3C/svg%3E" width="1005"/></p><noscript><img alt="Created Word Document" class="alignnone size-full wp-image-13503" height="619" sizes="(max-width: 1005px) 100vw, 1005px" src="img/c0e8c6605f52e31de7ba508ce15d0086.png" srcset="https://javabeginnerstutorial.com/wp-content/uploads/2018/06/6_WordCreatedDoc-1.jpg 1005w, https://javabeginnerstutorial.com/wp-content/uploads/2018/06/6_WordCreatedDoc-1-300x185.jpg 300w, https://javabeginnerstutorial.com/wp-content/uploads/2018/06/6_WordCreatedDoc-1-768x473.jpg 768w" width="1005"/><p>创建的Word文档,所有代码文件和JAR文件都放置在<a href="https://github.com/JBTAdmin/Selenium"> GitHub存储库</a>中,以便于访问。 您可以为存储库加注星标和分支以方便使用。 请仔细阅读“ README.md”文件以获取明确说明。</p><p>编码愉快! 祝你今天愉快!</p><div class="sticky-nav" style="font-size: 15px;"><div class="sticky-nav-image"></div><div class="sticky-nav-holder"><div class="sticky-nav_item"><h6 class="heading-sm">下一篇文章</h6></div><h5 class="sticky-nav_heading " style="font-size: 15px;"><a href="https://javabeginnerstutorial.com/selenium/10h-advanced-webdriver-sending-email-with-attachments/" title="10h. Advanced WebDriver – Sending email with attachments"> 10小时。 高级WebDriver –发送带有附件的电子邮件</a></h5></div></div> </body> </html></noscript>