当页面使用前端ajax方式渲染的页面数据时,页面会使用js请求ajaxUrl获取json格式数据时,而后再用js把数据解析并渲染到页面的指定位置上。html
当爬虫要住区ajaxUrl返回的json格式数据时,我当时是这样写的:前端
// 声明:下面这种方法是错误的。是我没有看官方demo的时候凭感受写出的解析json数据的代码。 JsonPathSelector json = new JsonPathSelector(page.getRawText()); List<String> name = json.selectList("$.data.itemList[*].brand.name"); List<String> uri = json.selectList("$.data.itemList[*].brand.uri");
看了官方us.codecraft.webmagic.selector.JsonPathSelectorTest,才知道原来参数写错了。java
JsonPathSelector(String jsonPathStr)这个构造函数的参数是jsonPathStr,也就是提取规则的字符串。web
String select(String text)方法和List<String> selectList(String text)方法,参数都是text,也就是json的字符串。ajax
package us.codecraft.webmagic.selector; import org.junit.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * @author code4crafter@gmai.com <br> */ public class JsonPathSelectorTest { private String text = "{ \"store\": {\n" + " \"book\": [ \n" + " { \"category\": \"reference\",\n" + " \"author\": \"Nigel Rees\",\n" + " \"title\": \"Sayings of the Century\",\n" + " \"price\": 8.95\n" + " },\n" + " { \"category\": \"fiction\",\n" + " \"author\": \"Evelyn Waugh\",\n" + " \"title\": \"Sword of Honour\",\n" + " \"price\": 12.99,\n" + " \"isbn\": \"0-553-21311-3\"\n" + " }\n" + " ],\n" + " \"bicycle\": {\n" + " \"color\": \"red\",\n" + " \"price\": 19.95\n" + " }\n" + " }\n" + "}"; @Test public void testJsonPath() { System.out.println("须要解析的json:"+text); JsonPathSelector jsonPathSelector = new JsonPathSelector("$.store.book[*].author"); String select = jsonPathSelector.select(text); List<String> list = jsonPathSelector.selectList(text); assertThat(select).isEqualTo("Nigel Rees"); assertThat(list).contains("Nigel Rees","Evelyn Waugh"); jsonPathSelector = new JsonPathSelector("$.store.book[?(@.category == 'reference')]"); list = jsonPathSelector.selectList(text); select = jsonPathSelector.select(text); System.out.println("select方法的结果:\t"+select); System.out.println("selectList方法的结果:\t"+list); assertThat(select).isEqualTo("{\"author\":\"Nigel Rees\",\"price\":8.95,\"category\":\"reference\",\"title\":\"Sayings of the Century\"}"); assertThat(list).contains("{\"author\":\"Nigel Rees\",\"price\":8.95,\"category\":\"reference\",\"title\":\"Sayings of the Century\"}"); } }
我以为这个实现不太好。在一个page中,jsonStr是同样的,而提取规则不一样。若是每次都new 一个新的JsonPathSelector做为提取规则,那要建立多少对象啊。并且和下面这种实现比较来讲,提取规则开发方式不一样:json
String brand_price = html.xpath("//span[@id=\"item-sellprice\"]/text()").toString(); String brand_img = html.xpath("//img[@id=\"brand-img\"]/@src").toString(); String brand_describe = html.xpath("//p[@id=\"brand-describe\"]/text()").toString(); String location_text = html.xpath("//span[@id=\"location-text\"]/text()").toString();
估计不是我本身出现这种问题吧,因此就记录一下。嘿嘿。api