Selenium ..提取数据然后将其存储在txt文件中

时间:2016-12-01 07:25:28

标签: java selenium

    WebDriver driver = new ChromeDriver();

      driver.get("http://edition.cnn.com/");
      Thread.sleep(4000);

                driver.findElement(By.id("search-button")).click();
                driver.findElement(By.id("search-input-field")).sendKeys("Sport");
                driver.findElement(By.id("submit-button")).click();

                List<WebElement> allLinks = driver.findElements(By.className("cd__headline"));

                for (  int i=0 ; i<allLinks.size();i++)
                {
                   try {


                        File file = new File("file path");


                        FileWriter fw = new FileWriter(file.getAbsoluteFile());
                        BufferedWriter bw = new BufferedWriter(fw);
                        bw.write(((WebElement) allLinks.get(i)).getText());
                           System.out.println(((WebElement) allLinks.get(i)).getText());
                        bw.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                }

                System.out.println(driver.getTitle());
                driver.manage().window().maximize();
            }   // driver.close();


                //driver.quit();
    }

你好程序员; 我遇到了一个问题,即创建一个从网页中提取数据然后将其存储在txt文件中的程序,

这个问题我只得到了10个头条中的一个!!

1 个答案:

答案 0 :(得分:0)

通过将true作为第二个参数传递来将FileWriter转换为追加模式。

FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);

或者您可以在for循环之外移动打开和关闭文件,如下所示:

    public static void main(String[]args ) {
    WebDriver driver = new ChromeDriver();
    driver.get("http://edition.cnn.com/");
    Thread.sleep(4000);
    driver.findElement(By.id("search-button")).click();
    driver.findElement(By.id("search-input-field")).sendKeys("Sport");
    driver.findElement(By.id("submit-button")).click();

    List<WebElement> allLinks = driver.findElements(By.className("cd__headline"));

    try {
        File file = new File("file");
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        for (  int i=0 ; i<allLinks.size();i++)
        {
                bw.write(((WebElement) allLinks.get(i)).getText());
                System.out.println(((WebElement) allLinks.get(i)).getText());
            }
            bw.close();
        }
    catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(driver.getTitle());
    driver.manage().window().maximize();
}   // driver.close();