Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save data into a file using Selenium

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.

like image 852
Kamran Xeb Avatar asked Mar 08 '26 05:03

Kamran Xeb


1 Answers

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.
like image 72
Naveen Kumar R B Avatar answered Mar 10 '26 18:03

Naveen Kumar R B