htmlcleaner+xpath爬取

有两个问题,记录一下 :

1、xpath如下格式(通过firebug下面的xpath插件获得的路径):

    

  html/body/div[2]/div[1]/div[3]/ul/li/div/div/span/span[2]

此时htmlcleaner调用xpath查找元素的方法找不到该元素(确定及肯定该界面有这元素),将路径修改为:

    

  /body/div[2]/div[1]/div[3]/ul/li/div/div/span/span[2]

就可以爬取到了。

2、爬取元素的代码:(记录一下啦)

Document doc = getDocument(url);
		if(doc!=null && doc.hasText()){
//			System.out.println(doc.html());
		    String document = formatContext(doc.html());
		    System.out.println(document);
		    
			TagNode node = cleaner.clean(document);

			Object[] ns = null;
			try {
				ns = node.evaluateXPath(xpath);
			} catch (XPatherException e) {
				e.printStackTrace();
			}
			if (ns.length > 0) {
				for (Object on : ns) {
					TagNode n = (TagNode) on;
                               //下面的两个方法都可以取到标签里面的内容
                                String text = cleaner.getInnerHtml(n);
			     	System.out.println(text);
					System.out.println(url + n.getText().toString());

				}
			} else {
				return null;// 规则不对,返回空
			}

你可能感兴趣的:(xpath,HTMLCleaner)