Wednesday, April 20, 2016

HTML File Parsing using XPATH


The javax.xml parsers DO NOT work as it takes ONLY WELL formatted xml file. Use Selenium and open local html file in driver.get("file:///d:/somefile.html") and use the normal driver.findElement(By.xpath) etc., Use HtmlUnitDriver so that no browser is opened visually. Sample CODE import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.List; import java.util.concurrent.TimeUnit; public class Main { public static void main(String... args) { HtmlUnitDriver driver; try { driver = new HtmlUnitDriver(); driver.manage().timeouts().pageLoadTimeout(10000, TimeUnit.MILLISECONDS); driver.get("file:///" + "c:/localfile.html"); List storiesPassed = driver.findElements(By.xpath("//td[@class='story successful']")); List storiesFailed = driver.findElements(By.xpath("//td[@class='story failed']")); System.out.println( "H3 " + driver.findElement(By.tagName("h3")).getText()); System.out.println(); createHtmlBody(sBuffer, storiesPassed ); createHtmlBody(sBuffer, storiesFailed ); sBuffer.append(HtmlEnd); bw.write(sBuffer.toString()); bw.flush(); bw.close(); }catch(Exception e){ e.printStackTrace(); } } }

No comments:

Post a Comment