Validator.nu HTML Parserを使ってHTMLをXPathでパースしたいのですが、結果が返ってきません。
デバッグしていて、Documentの中身がnullではないがきちんと入っていないような感じです。
以下のコードのnodeの中身がnullのままです。
原因や解決策をご教授いただけないでしょうか。
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.net.URL; import java.util.HashMap; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import nu.validator.htmlparser.dom.HtmlDocumentBuilder; public class Foo { public static void main(String[] args) throws IOException { long t1 = System.currentTimeMillis(); response=new HashMap<>(); URL url= new URL("http://www.yahoo.co.jp"); String content=getSourceText(url); //System.out.println(content); HtmlDocumentBuilder builder = new HtmlDocumentBuilder(); StringReader reader = new StringReader(content); Document doc=null; try { //doc = builder.parse(new InputSource(new ByteArrayInputStream(content.getBytes("UTF-8")))); doc = builder.parse(new InputSource(reader)); } catch (SAXException e1) { e1.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Node node=null; try { //String fooString = xpath.evaluate("//*[@id=feed-tabs]/ul/li[1]/div",doc); //String fooString = xpath.evaluate("//*[@id=\"typhoon\"]",doc); //System.out.println(fooString); String path = "//*[@id=typhoon]"; node = (Node) xpath.evaluate(path,doc, XPathConstants.NODE); } catch (XPathExpressionException e) { e.printStackTrace(); } } public static String getSourceText(URL url) throws IOException { InputStream in = url.openStream(); StringBuilder sb = new StringBuilder(); try { BufferedReader bf = new BufferedReader(new InputStreamReader(in)); String s; while ((s=bf.readLine())!=null) { sb.append(s); } } finally { in.close(); } return sb.toString(); } }
参考にしたサイト
ちなみに、これまではjsoupを使っていたのですが、
・idの重複に対応していない(指定されたidの最初の要素しか取れない)
・パースしているwebサイトに改修が入った時に大幅にコーディングの直しが必要
ということでやめました。
cybernekoも使ったことはありますが、HTML5に対応していないようでした。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2016/09/09 05:47
2016/09/09 05:57