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)
}
}
这是我的代码,但没有将数据保存到文件中。
答案 0 :(得分: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 :(得分:0)
由于以下原因,数据未保存在文件中。请使用以下经过修改的(有效的)代码。
!filedata.isFile()
,并且始终为false。因此,需要将其更改为filedata.isFile()
FileWriter
对象没有关闭,需要执行添加操作后才需要关闭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();
}
}