package us.codecraft.webmagic.samples;

import org.apache.commons.collections.CollectionUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.JsonPathSelector;

import java.util.List;

/**
 * @author code4crafter@gmail.com
 * @since 0.5.0
 */
public class AngularJSProcessor implements PageProcessor {

    private Site site = Site.me();

    private static final String ARITICALE_URL = "http://angularjs\\.cn/api/article/\\w+";

    private static final String LIST_URL = "http://angularjs\\.cn/api/article/latest.*";

    @Override
    public void process(Page page) {
        if (page.getUrl().regex(LIST_URL).match()) {
            List<String> ids = new JsonPathSelector("$.data._id").selectList(page.getRawText());
            if (CollectionUtils.isNotEmpty(ids)) {
                for (String id : ids) {
                    page.addTargetRequest("http://angularjs\\.cn/api/article/" + id);
                }
            }
        } else {
            page.putField("title", new JsonPathSelector("$.title").select(page.getRawText()));
            page.putField("content", new JsonPathSelector("$.content").select(page.getRawText()));
        }

    }

    @Override
    public Site getSite() {
        return site;
    }
}

@@ -158,16 +158,53 @@
 c.Site;%0A
+import us.codecraft.webmagic.Spider;%0A
 import u
@@ -828,16 +828,19 @@
 (%22$.data
+%5B*%5D
 ._id%22).s
@@ -1011,34 +1011,32 @@
 http://angularjs
-%5C%5C
 .cn/api/article/
@@ -1152,16 +1152,21 @@
 ctor(%22$.
+data.
 title%22).
@@ -1254,16 +1254,21 @@
 ctor(%22$.
+data.
 content%22
@@ -1383,11 +1383,176 @@
 e;%0A    %7D
+%0A%0A    public static void main(String%5B%5D args) %7B%0A        Spider.create(new AngularJSProcessor()).addUrl(%22http://angularjs.cn/api/article/latest?p=1&s=20%22).run();%0A    %7D
 %0A%7D%0A

fix jsonpath in AngularJSProcessor