2020-06-02 jsoup java解析html

2020-06-02  本文已影响0人  lancelot123

https://jsoup.org/
https://github.com/zdongcoding/jsouplib

AJsoup

[图片上传失败...(image-697007-1591092692829)] [图片上传失败...(image-524d6e-1591092692829)] [图片上传失败...(image-800b7a-1591092692829)]

AJsoup 模块是快速将html 转换成bean 类似gson转换

依赖 jsoup

使用前提你了解jsoup并且了解jsoup的Select

Gradle

compile 'com.github.zdongcoding:ajsoup:0.1.0'

Maven

<dependency>
  <groupId>com.github.zdongcoding</groupId>
  <artifactId>ajsoup</artifactId>
  <version>0.1.0</version>
  <type>pom</type>
</dependency>

使用方法如下:

    bean.java

    @Select(select = "body")
    public class HomeBean {
        @Select(select = "div > div > div.listbox")
        public HotTopTabBean hotTopTabBean; //热门数据
        @Select(select = "div#nav > ul > li[id]", attr = "id")
        public Map<String, NavBean> navBeans;
        @Select(select = "div#nav-under > ul >li:has(a)")  //排除无 <a 标签
        public List<NavBean> navUnderBeans;
        @Select(select = "div#body > div.left.noborder.clearfix.block1 > ul")
        public List<LatestVideoBean> latests;
        @Select(select = "div#header-in > div > ul#hot-words > li")
        public List<WebBean> searchbeans;
    }
   String html=....;

   HomeBean bean=AJsoupReader.deserialize(Jsoup.parse(html), HomeBean.class);

AJsoup---->Converter-Ajsoup

使用过Retrofit 一看这个名字就知道做什么的

Gradle

compile 'com.github.zdongcoding:converter-ajsoup:0.1.0'

Maven

<dependency>
  <groupId>com.github.zdongcoding</groupId>
  <artifactId>converter-ajsoup</artifactId>
  <version>0.1.0</version>
  <type>pom</type>
</dependency>

使用方法:

    Api.java
     public interface Api {
        @GET("{url}")
        Observable<String> getPage(@Path(value = "url",encoded = true) String url);
     }
    api = new Retrofit.Builder().baseUrl(baseUri)
                .addConverterFactory(JsoupConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build().create(Api.class);

    api.getPage("").subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<HomeBean>() {
            @Override
            public void onCompleted() {
            }
            @Override
            public void onError(Throwable e) {
            }
            @Override
            public void onNext(HomeBean homeBean) {
                view.setText(homeBean.toString());
            }
        });

选择器概要(Selector overview)

主要用到以上字段

不需要服务器 就可以做一个快速做一个客户端

完毕,就是这么简单

上一篇下一篇

猜你喜欢

热点阅读