android爬虫-Fruit

效果图

网站效果:


TIM截图20181113145717.png

手机展示:


aa.gif

概述

Fruit是一个解析html的框架。可以将html文件解析成本地实体文件。

Fruit地址:https://github.com/ghuiii/Fruit

解析的网址为:http://www.wyl.cc/tag/xinlingjitang/page/1

配合Rxjava、okhttp、retrofit使用

导包

compile 'io.reactivex.rxjava2:rxjava:2.1.3'
compile 'com.squareup.retrofit2:retrofit:2.3.0'

compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'

/*解析html*/
compile 'me.ghui:fruit-converter-retrofit:1.0.5'
compile 'me.ghui:global-retrofit-converter:1.0.1'

/*converter-gson 用于将请求结果转换为实体类型*/
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
/*converter-scalars 用于将请求结果转换为基本类型,一般为String*/
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'

注意

刚开始因为用了 converter:1.0.4导致一直报错:

Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.

应该是和后面导入的converter-gson或者是converter-scalars不兼容。当改成fruit-converter-retrofit:1.0.5后问题解决。

初始化 OkHttp Retrofit Fruit

基本配置

public class ApiStrategy {

    //读超时长,单位:毫秒
    public static final int READ_TIME_OUT = 7676;
    //连接时长,单位:毫秒
    public static final int CONNECT_TIME_OUT = 7676;


    /**
     * 设缓存有效期为两天
     */
    private static final long CACHE_STALE_SEC = 60 * 60 * 24 * 2;


    public static QuotaionsApis apiService;
    private Fruit mFruit;

    public static QuotaionsApis getApiService() {
        if (apiService == null) {
            synchronized (Api.class) {
                if (apiService == null) {
                    new ApiStrategy();
                }
            }
        }
        return apiService;
    }

    private ApiStrategy() {
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //缓存
        File cacheFile = new File(MyApplication.getContextObject().getCacheDir(), "cache");
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb

        //增加头部信息
        Interceptor headerInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request build = chain.request().newBuilder()
                        //.addHeader("Content-Type", "application/json")//设置允许请求json数据
                        .build();
                return chain.proceed(build);
            }
        };

        //创建一个OkHttpClient并设置超时时间
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(READ_TIME_OUT, TimeUnit.MILLISECONDS)
                .connectTimeout(CONNECT_TIME_OUT, TimeUnit.MILLISECONDS)
                .addInterceptor(mRewriteCacheControlInterceptor)
                .addNetworkInterceptor(mRewriteCacheControlInterceptor)
                .addInterceptor(headerInterceptor)
                .addInterceptor(logInterceptor)
                .cache(cache)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(Constant.BASE_URL)
//                .addConverterFactory(GsonConverterFactory.create())//请求的结果转为实体类
                //适配RxJava2.0,RxJava1.x则为RxJavaCallAdapterFactory.create()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GlobalConverterFactory.create().add(FruitConverterFactory.create(getFruit()), Html.class))
                .build();
        apiService = retrofit.create(QuotaionsApis.class);


    }


    /**
     * 云端响应头拦截器,用来配置缓存策略
     * Dangerous interceptor that rewrites the server's cache-control header.
     */
    private final Interceptor mRewriteCacheControlInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            String url = request.url().toString();

            Log.i("http", url);
            String cacheControl = request.cacheControl().toString();
            if (!NetworkUtil.isNetworkConnected(MyApplication.getContextObject())) {
                request = request.newBuilder()
                        .cacheControl(TextUtils.isEmpty(cacheControl) ? CacheControl
                                .FORCE_NETWORK : CacheControl.FORCE_CACHE)
                        .build();
            }
            Response originalResponse = chain.proceed(request);
            if (NetworkUtil.isNetworkConnected(MyApplication.getContextObject())) {
                return originalResponse.newBuilder()
                        .header("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build();
            } else {
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=" +
                                CACHE_STALE_SEC)
                        .removeHeader("Pragma")
                        .build();
            }
        }
    };

    private Fruit getFruit() {
        if (mFruit == null) {
            mFruit = new Fruit();
        }
        return mFruit;
    }

}

配置请求参数

和基本的retrofit参数类似


public interface QuotaionsApis {
    //使用动态 url 匹配
    @GET
    @Html
    Observable<QuotationsBean> getQuotationsBean(@Url String url);
}

根据网页结构得到相应的字段

TIM截图20181113145228.png

对应的实体如下:

public class QuotationsBean {


    @Pick(value = "article")
    private List<QuotationsBeanItem> quotationsBeanItemList;
    
    ...

    public static class QuotationsBeanItem {
        //图片
        @Pick(value = "img", attr = Attrs.SRC)
        private String img;
        @Pick(value = "h2.entry-title > a")
        private String title;
        @Pick(value = "div.archive-content")
        private String content;
        @Pick(value = "span.entry-meta > span")
        private String time;
        @Pick(value = "h2.entry-title > a", attr = Attrs.HREF)
        private String link;
        @Pick(value = "span.cat > a")
        private String tag; 
        ...
    }

根据视图结构便可以得到对应的数据。

完成响应 进行请求

 ApiMethods.getQuotations(new MyObserver<QuotationsBean>(MainActivity.this, new ObserverOnNextListener<QuotationsBean>() {
            @Override
            public void onNext(QuotationsBean quotationsBean) {
                List<QuotationsBean.QuotationsBeanItem> listData = quotationsBean.getQuotationsBeanItemList();
                if (page == 1) {
                    mList.clear();
                    mList.addAll(listData);
                    refreshLayout.finishRefresh(1000);
                } else if (page > 0) {
                    mList.addAll(listData);
                    refreshLayout.finishLoadMore(1000/*,false*/);
                }
                mAdapter.notifyDataSetChanged();
            }
        }), Constant.QUOTATIONS_URL + String.valueOf(page));

github传送门

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容