首页 > 学院 > 开发设计 > 正文

使用JSoup解析html文档

2019-11-06 06:59:59
字体:
来源:转载
供稿:网友

简介:

jsoup 是一款java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据。

使用:

1)加载一个Url

Document doc = Jsoup.connect("http://example.com/").get();String title = doc.title();2)加载一个本地文档:

String html = "<div><p>Lorem ipsum.</p>";Document doc = Jsoup.parseBodyFragment(html);Element body = doc.body();
File input = new File("/tmp/input.html");Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");("http://example.com/"参数用于解决文件中URLs是相对路径的问题,如果不需要可以传入一个空的字符串。)

3)实例:获取google play应用的版本信息

                String url = "https://play.google.com/store/apps/details?id=com.modbus.light";                try {                    Connection connection = Jsoup.connect(url);//初始化连接                    Document doc = connection.get();//获取文档对象                    Element element = doc.select("div.meta-info").get(2);//找到div标签class为meta-info的位置                    Element content = element.child(1);                    String version = content.childNode(0).toString()..replaceAll("[^1-9]", "");                    System.out.PRintln(“线上最新版本:“+version);                } catch (Exception e) {                    e.printStackTrace();                }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表