如何使用Selenium将数据保存到文件中

3
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)
    }
}

这是我的代码,但它没有将数据保存到文件中。


System.out.println(dataoutput); 这一行代码会输出什么内容? - cruisepandey
将从网页元素中找到的文本打印到控制台的代码改为将其保存到CSV文件中。 - Kamran Xeb
你可以尝试使用 PrintWriter pw = new PrintWriter(new File("test.csv")); StringBuilder sb = new StringBuilder(); sb.append(dataoutput); - cruisepandey
在“test.csv”的位置上,请放置您的CSV文件路径。 - cruisepandey
你想要添加到一个txt文件或csv文件中。 - dangi13
2个回答

1
以下代码对我有效:

    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. 由于我们正在创建一个新文件,因此删除了文件检查。
  2. 使用WebDriverWait添加了显式等待,以等待表格元素显示。
  3. 将FileWriter保留在try块中,因为它对我来说会导致编译问题。这个语法的好处是它会自动关闭fileWriter对象。

0

由于以下原因,数据未保存在文件中。 请使用以下修改后的(工作)代码。

  1. 在if条件中,添加了!filedata.isFile(),它始终为false。 因此,需要将其更改为filedata.isFile()
  2. FileWriter对象未关闭,并且需要在执行附加操作后关闭
  3. 作为最佳实践,在启动URL后添加一些等待时间。否则,元素将无法正确找到,并且将抛出NoSuchElementException异常

代码:

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");

    //Wait is addeded for the Page Load completion 
    WebDriverWait wait=new WebDriverWait(driver,20);
    wait.until(ExpectedConditions.titleContains("Premier"));


    WebElement table;

    table = driver.findElement(By.xpath("//*[@id=\"mainContent\"]/div/div[1]/div[3]/div/div"));

    String dataoutput = table.getText();
    System.out.println(dataoutput);


    File filedata = new File("src/main/table.csv");

    //Not Equal condition is modified
    if (filedata.exists() && filedata.isFile()) {
        FileWriter writecsv = new FileWriter(filedata);
        String datas = dataoutput;
        writecsv.append(dataoutput)
        writecsv.close();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接