就爬取和解析内容而言,咱们有太多选择。
好比,不少人都以为Jsoup就能够解决全部问题。
不管是Http请求、DOM操做、CSS query selector筛选都很是方便。
关键是这个selector,仅经过一个表达式筛选出的只能是一个node。
如过我想得到一个text或者一个node的属性值,我须要从返回的element对象中再获取一次。
而我刚好接到了一个有意思的需求,仅经过一个表达式表示想筛选的内容,获取一个新闻网页的每一条新闻的标题、连接等信息。 html
XPath再合适不过了,好比下面这个例子: java
static void crawlByXPath(String url,String xpathExp) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException { String html = Jsoup.connect(url).post().html(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(html); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); XPathExpression expression = xPath.compile(xpathExp); expression.evaluate(html); }
遗憾的是,几乎没有网站能够经过documentBuilder.parse这段代码。
而XPath却对DOM很是严格。
对HTML进行一次clean,因而我加入了这个东西:node
<dependency> <groupId>net.sourceforge.htmlcleaner</groupId> <artifactId>htmlcleaner</artifactId> <version>2.9</version> </dependency>
HtmlCleaner能够帮我解决这个问题,并且他自己就支持XPath。
仅仅一行HtmlCleaner.clean就解决了:express
public static void main(String[] args) throws IOException, XPatherException { String url = "http://zhidao.baidu.com/daily"; String contents = Jsoup.connect(url).post().html(); HtmlCleaner hc = new HtmlCleaner(); TagNode tn = hc.clean(contents); String xpath = "//h2/a/@href"; Object[] objects = tn.evaluateXPath(xpath); System.out.println(objects.length); }
可是HtmlCleaner又引起了新的问题,当我把表达式写成"//h2/a[contains(@href,'daily')]/@href"时,他提示我不支持contains函数。
而javax.xml.xpath则支持函数使用,这下问题来了。
如何结合两者? HtmlCleaner提供了DomSerializer,能够将TagNode对象转为org.w3c.dom.Document对象,好比:dom
Document dom = new DomSerializer(new CleanerProperties()).createDOM(tn);
如此一来就能够发挥各自长处了。 函数
public static void main(String[] args) throws IOException, XPatherException, ParserConfigurationException, XPathExpressionException { String url = "http://zhidao.baidu.com/daily"; String exp = "//h2/a[contains(@href,'daily')]/@href"; String html = null; try { Connection connect = Jsoup.connect(url); html = connect.get().body().html(); } catch (IOException e) { e.printStackTrace(); } HtmlCleaner hc = new HtmlCleaner(); TagNode tn = hc.clean(html); Document dom = new DomSerializer(new CleanerProperties()).createDOM(tn); XPath xPath = XPathFactory.newInstance().newXPath(); Object result; result = xPath.evaluate(exp, dom, XPathConstants.NODESET); if (result instanceof NodeList) { NodeList nodeList = (NodeList) result; System.out.println(nodeList.getLength()); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); System.out.println(node.getNodeValue() == null ? node.getTextContent() : node.getNodeValue()); } } }