WebMagic学习-解析json
生活随笔
收集整理的這篇文章主要介紹了
WebMagic学习-解析json
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
這篇文章要解決什么
當頁面使用前端ajax方式渲染的頁面數據時,頁面會使用js請求ajaxUrl獲取json格式數據時,然后再用js把數據解析并渲染到頁面的指定位置上。
?
錯誤寫法
當爬蟲要住區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,才知道原來參數寫錯了。
?
正確寫法
JsonPathSelector(String jsonPathStr)這個構造函數的參數是jsonPathStr,也就是提取規則的字符串。
String select(String text)方法和List<String> selectList(String text)方法,參數都是text,也就是json的字符串。
?
Demo
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" +"}";@Testpublic 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作為提取規則,那要創建多少對象啊。而且和下面這種實現比較來說,提取規則開發方式不同:
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();估計不是我自己出現這種問題吧,所以就記錄一下。嘿嘿。
轉載于:https://my.oschina.net/anxiaole/blog/782026
總結
以上是生活随笔為你收集整理的WebMagic学习-解析json的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java笔试面试题二(常考问答)转
- 下一篇: opencv环境搭建