How to save data into a file using Selenium

Kamran Xeb :
public static void main(String[] args) throws IOException {

    System.setProperty("src/driver/chromedriver", "G:\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.premierleague.com/tables");

    WebElement table;

    table = driver.findElement(By.xpath("//*[@id=\"mainContent\"]/div/div[1]/div[3]/div/div"));
    String dataoutput;
    dataoutput = table.getText();
    System.out.println(dataoutput);

    String csvOutputFile = "table.csv";

    File filedata = new File("src/main/table.csv");
    if (filedata.exists() && !filedata.isFile()) {
        FileWriter writecsv = new FileWriter("src/main/table.csv");
        String datas = dataoutput;
        writecsv.append(dataoutput)
    }
}

This is my code but it isn't saving data to file.

Naveen Kumar R B :

The following code worked for me:

    driver.get("https://www.premierleague.com/tables");

    WebElement table;

    WebDriverWait wait = new WebDriverWait(driver, 30);
    table = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"mainContent\"]/div/div[1]/div[3]/div/div")));
    String dataoutput;
    dataoutput = table.getText();
    System.out.println(dataoutput);

    String csvOutputFile = "table.csv";

    try(FileWriter writecsv = new FileWriter("src/main/table.csv")) {
        writecsv.append(dataoutput);
    }
  1. File checking is removed, as we are creating a new file here.
  2. Added explicit wait using WebDriverWait, to wait for the table element to be displayed.
  3. kept FileWriter inside try block as it was giving compilation issues for me. The good thing with this syntax is it automatically closed the fileWriter object.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=108563&siteId=1