使用webmagic爬虫的时候,有时候返回的数据是json字符串,就需要对其进行解析,其中自带的工具类JsonPathSelector很强大。笔记走一波
maven包
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-core</artifactId>
<version>0.7.3</version>
</dependency>
使用范例
import java.util.List;
import us.codecraft.webmagic.selector.JsonPathSelector;
public class JsonSelect {
public static void main(String[] args) {
//json字符串
String jsonStr = "{\"head\": [ {\"text\":\"广州\",\"id\":\"广州\",\"pid\":\"广东省\"}, {\"text\":\"郑州\",\"id\":\"郑州\",\"pid\":\"河南省\"}] } ";
//字符串转json
// JSONObject json = JSONObject.parseObject(jsonStr);
//json解析获得所有text
List<String> id = new JsonPathSelector("$.head[*].text").selectList(jsonStr);
//获取郑州
String city = new JsonPathSelector("$.head[1].text").select(jsonStr);
//
System.out.println(id.toString());
System.out.println(city);
}
}
结果展示