android爬蟲-Fruit

效果圖

網(wǎng)站效果:


TIM截圖20181113145717.png

手機(jī)展示:


aa.gif

概述

Fruit是一個(gè)解析html的框架∥鸸可以將html文件解析成本地實(shí)體文件。

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

解析的網(wǎng)址為:http://www.wyl.cc/tag/xinlingjitang/page/1

配合Rxjava、okhttp爽彤、retrofit使用

導(dǎo)包

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 用于將請(qǐng)求結(jié)果轉(zhuǎn)換為實(shí)體類型*/
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
/*converter-scalars 用于將請(qǐng)求結(jié)果轉(zhuǎn)換為基本類型,一般為String*/
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'

注意

剛開始因?yàn)橛昧?converter:1.0.4導(dǎo)致一直報(bào)錯(cuò):

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

應(yīng)該是和后面導(dǎo)入的converter-gson或者是converter-scalars不兼容缚陷。當(dāng)改成fruit-converter-retrofit:1.0.5后問題解決适篙。

初始化 OkHttp Retrofit Fruit

基本配置

public class ApiStrategy {

    //讀超時(shí)長(zhǎng),單位:毫秒
    public static final int READ_TIME_OUT = 7676;
    //連接時(shí)長(zhǎng)箫爷,單位:毫秒
    public static final int CONNECT_TIME_OUT = 7676;


    /**
     * 設(shè)緩存有效期為兩天
     */
    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")//設(shè)置允許請(qǐng)求json數(shù)據(jù)
                        .build();
                return chain.proceed(build);
            }
        };

        //創(chuàng)建一個(gè)OkHttpClient并設(shè)置超時(shí)時(shí)間
        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())//請(qǐng)求的結(jié)果轉(zhuǎn)為實(shí)體類
                //適配RxJava2.0,RxJava1.x則為RxJavaCallAdapterFactory.create()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GlobalConverterFactory.create().add(FruitConverterFactory.create(getFruit()), Html.class))
                .build();
        apiService = retrofit.create(QuotaionsApis.class);


    }


    /**
     * 云端響應(yīng)頭攔截器嚷节,用來配置緩存策略
     * 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;
    }

}

配置請(qǐng)求參數(shù)

和基本的retrofit參數(shù)類似


public interface QuotaionsApis {
    //使用動(dòng)態(tài) url 匹配
    @GET
    @Html
    Observable<QuotationsBean> getQuotationsBean(@Url String url);
}

根據(jù)網(wǎng)頁結(jié)構(gòu)得到相應(yīng)的字段

TIM截圖20181113145228.png

對(duì)應(yīng)的實(shí)體如下:

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; 
        ...
    }

根據(jù)視圖結(jié)構(gòu)便可以得到對(duì)應(yīng)的數(shù)據(jù)。

完成響應(yīng) 進(jìn)行請(qǐng)求

 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傳送門

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末虎锚,一起剝皮案震驚了整個(gè)濱河市硫痰,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌窜护,老刑警劉巖效斑,帶你破解...
    沈念sama閱讀 217,185評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異柄慰,居然都是意外死亡鳍悠,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門坐搔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來藏研,“玉大人,你說我怎么就攤上這事概行〈赖玻” “怎么了?”我有些...
    開封第一講書人閱讀 163,524評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)业踏。 經(jīng)常有香客問我禽炬,道長(zhǎng),這世上最難降的妖魔是什么勤家? 我笑而不...
    開封第一講書人閱讀 58,339評(píng)論 1 293
  • 正文 為了忘掉前任腹尖,我火速辦了婚禮,結(jié)果婚禮上伐脖,老公的妹妹穿的比我還像新娘热幔。我一直安慰自己,他們只是感情好讼庇,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,387評(píng)論 6 391
  • 文/花漫 我一把揭開白布绎巨。 她就那樣靜靜地躺著,像睡著了一般蠕啄。 火紅的嫁衣襯著肌膚如雪场勤。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,287評(píng)論 1 301
  • 那天歼跟,我揣著相機(jī)與錄音和媳,去河邊找鬼。 笑死哈街,一個(gè)胖子當(dāng)著我的面吹牛窗价,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播叹卷,決...
    沈念sama閱讀 40,130評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼坪它!你這毒婦竟也來了骤竹?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,985評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤往毡,失蹤者是張志新(化名)和其女友劉穎蒙揣,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體开瞭,經(jīng)...
    沈念sama閱讀 45,420評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡懒震,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,617評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了嗤详。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片个扰。...
    茶點(diǎn)故事閱讀 39,779評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖葱色,靈堂內(nèi)的尸體忽然破棺而出递宅,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 35,477評(píng)論 5 345
  • 正文 年R本政府宣布办龄,位于F島的核電站烘绽,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏俐填。R本人自食惡果不足惜安接,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,088評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望英融。 院中可真熱鬧盏檐,春花似錦、人聲如沸矢赁。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽撩银。三九已至给涕,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間额获,已是汗流浹背蚁吝。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工绵载, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,876評(píng)論 2 370
  • 正文 我出身青樓袍镀,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親蚂夕。 傳聞我的和親對(duì)象是個(gè)殘疾皇子锹漱,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,700評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容