有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Selenium将值写入。txt文件

我试图从一个网页中提取一些值,目的是将它们写入一个文档。手动验证的txt文件。我环顾了网络,在我的场景中找不到实现这一点的方法。如果可能的话,我将用java编写代码

我为元素提供了以下html代码:

<td class="value" data-bind="text: 
$data.value">Windows Server 2012 R2 Standard 64-bit</td>

元素的xpath是:

html/body/div[4]/div/div[4]/div[2]/div[4]/div/div[1]/div[1]/table[1]/tbody/tr[2]/td[2]

有没有人能帮我创建一段示例代码,它将:

a)提取值并将其写入文本文件。最好是前缀为“操作系统”。
b)用唯一的ID保存文件,我的想法是在文件名后面加上日期戳。
c)我将有多个元素从网页中读取,然后写入文本文件,大约8个,在将多个值写入一个文件时,我需要考虑哪些因素。txt文件并整齐地格式化

希望我已经包括了所有我需要在这里,如果不只是问

非常感谢。千克


共 (2) 个答案

  1. # 1 楼答案

    这并不像看上去那么难。我使用类似的函数将日志写入txt文件

    首先,我将把所有信息写在一个字符串变量中。在将信息写入变量之前格式化信息是很有帮助的。如果您收集了所有信息,您可以使用以下代码将此字符串非常简单地写入txt文件:

    private static void printToTxt(){
    
    String info = "Collected Informations";
    String idForTxtFile = new SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(new Date());
    File file = new File("Filename" + idForTxtFile);
    
    try {
      FileWriter fw = new FileWriter(file, true);
    
      //if you want to write the linesperator ("\n) as they are in the txt you should use the following Code:
    
      String lineSeparator = System.getProperty("line.separator");
      String[] ouput = info.split("\n");
    
      for (int i = 0; i <= output.length-1; i++) {
        fw.write(output[i]);
        fw.write(lineSeparator);
      }
    
      //instead you could only use:
      fw.write(info);
    
      fw.flush();
      fw.close();
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println(e.getLocalizedMessage);
    }
    

    有点晚了,但这是我的版本,也许你可以在你的版本中使用一些额外的版本

  2. # 2 楼答案

    我已经复习了关于问题How do I create a file and write to it in Java?的答案,谢谢你的轻推@Mardoz,通过一些游戏,我让它做我需要的事情。以下是最终代码,日期也被标记到文件名中:

    Date date = new Date() ;
        SimpleDateFormat dateFormat = new SimpleDateFormat("DD-MM-yyyy HH-mm") ;
    
        //      Wait for the element to be available
        new WebDriverWait(Login.driver,10).until(ExpectedConditions.visibilityOfElementLocated
                (By.xpath("html/body/div[4]/div/div[4]/div[2]/div[4]/div/div[1]/div[1]/table[1]/tbody/tr[2]/td[2]")));
    
        Writer writer = null;
    
        //      Find the value and write it to the text file 'Smoke_004 DD-MM-yyyy HH-mm.txt'
        try {
            writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream("Smoke_004 " + dateFormat.format(date) + ".txt"), "utf-8"));
            writer.write("Operating System : " + Login.driver.findElement
                    (By.xpath("html/body/div[4]/div/div[4]/div[2]/div[4]/div/div[1]/div[1]/table[1]/tbody/tr[2]/td[2]"))
                        .getText());
    
               } catch (IOException ex) {
            // report
        } finally {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    

    感谢@Mardoz和@erstwhileii的参与