使用Jsoup 抓取页面的数据

需要使用的是jsoup-1.7.3.jar包,如果需要看文档可以到官网:http://jsoup.org/  

1、在java中使用

import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JsoupTest {
    static String url="http://blog.csdn.net/zapperbot";
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        BolgBody();
    }

    /**
     * 获取指定HTML 文档指定的body
     * @throws IOException
     */
    private static void BolgBody() throws IOException {
        // 直接从字符串中输入 HTML 文档
        String html = "<html><head><title>zapperbot</title></head>"
                + "<body><p> 这里是 jsoup 项目的相关文章 </p></body></html>";
        Document doc = Jsoup.parse(html);
        System.out.println(doc.body());

        //  URL 直接加载 HTML 文档
        Document doc2 = Jsoup.connect(url).get();
        String title = doc2.body().toString();
        System.out.println(title);
    }

    /**
     * 获取博客上的文章标题和链接
     */
    public static void article() {
        Document doc;
        try {
            doc = Jsoup.connect("http://blog.csdn.net/zapperbot").get();
            Elements ListDiv = doc.getElementsByAttributeValue("class","postTitle");
            for (Element element :ListDiv) {
                Elements links = element.getElementsByTag("a");
                for (Element link : links) {
                    String linkHref = link.attr("href");
                    String linkText = link.text().trim();
                    System.out.println(linkHref);
                    System.out.println(linkText);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取指定博客文章的内容
     */
    public static void Blog() {
        Document doc;
        try {
            doc = Jsoup.connect("http://blog.csdn.net/zapperbot").get();
            Elements ListDiv = doc.getElementsByAttributeValue("class","postBody");
            for (Element element :ListDiv) {
                System.out.println(element.html());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


2、在Android中使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical" >

    <WebView
            android:id="@+id/webView"
            android:layout_width="fill_parent"
            android:layout_height="200dp" />

    <ScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

        <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/hello_world" />
    </ScrollView>
</LinearLayout>
异步加载数据,需要注意乱码,并且要添加获取网络权限

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.widget.TextView;

public class MainActivity extends Activity {
    private WebView webView;
    private TextView textView;
    private static final int DIALOG_KEY = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webView = (WebView) findViewById(R.id.webView);
        textView=(TextView) findViewById(R.id.textView);
        try {
            ProgressAsyncTask asyncTask=new ProgressAsyncTask(webView,textView);
            asyncTask.execute(10000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  String test() {
        StringBuffer buffer=new StringBuffer();
        Document doc;
        try {
            doc = Jsoup.connect("http://blog.csdn.net/zapperbot").get();
            Elements ListDiv = doc.getElementsByAttributeValue("class","postTitle");
            for (Element element :ListDiv) {
                Elements links = element.getElementsByTag("a");
                for (Element link : links) {
                    String linkHref = link.attr("href");
                    String linkText = link.text().trim();
                    buffer.append("linkHref=="+linkHref);
                    buffer.append("linkText=="+linkText);

                    System.out.println(linkHref);
                    System.out.println(linkText);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();

    }

    // 弹出"查看"对话框
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_KEY: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage("获取数据中  请稍候...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
        }
        return null;
    }

    public static String readHtml(String myurl) {
        StringBuffer sb = new StringBuffer("");
        URL url;
        try {
            url = new URL(myurl);
            BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(), "gbk"));
            String s = "";
            while ((s = br.readLine()) != null) {
                sb.append(s + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    class ProgressAsyncTask extends AsyncTask<Integer, Integer, String> {

        private WebView webView;
        private TextView textView;
        public ProgressAsyncTask(WebView webView,TextView textView) {
            super();
            this.webView=webView;
            this.textView=textView;
        }

        /**
         * 这里的Integer参数对应AsyncTask中的第一个参数 这里的String返回值对应AsyncTask的第三个参数
         * 该方法并不运行在UI线程当中,主要用于异步操作,所有在该方法中不能对UI当中的空间进行设置和修改
         * 但是可以调用publish Progress方法触发onProgressUpdateUI进行操作
         */
        @Override
        protected String doInBackground(Integer... params) {
            String str =null;
            Document doc = null;
            try {
                //String url ="http://blog.csdn.net/zapperbot";
                //doc= Jsoup.parse(new URL(url).openStream(),"utf-8", url);
                //doc = Jsoup.parse(readHtml(url));
                //doc=Jsoup.connect(url).get();
                //str=doc.body().toString();
                doc = Jsoup.connect("http://blog.csdn.net/zapperbot").get();
                Elements ListDiv = doc.getElementsByAttributeValue("class","postBody");
                for (Element element :ListDiv) {
                    str=element.html();
                    System.out.println(element.html());
                }
                Log.d("doInBackground", str.toString());
                System.out.println(str);
                //你可以试试GBKUTF-8
            } catch (Exception e) {
                e.printStackTrace();
            }
            return str.toString() ;
            //return test();
        }

        /**
         * 这里的String参数对应AsyncTask中的第三个参数(也就是接收doInBackground的返回值)
         * doInBackground方法执行结束之后在运行,并且运行在UI线程当中 可以对UI空间进行设置
         */
        @Override
        protected void onPostExecute(String result) {
            webView.loadData(result, "text/html;charset=utf-8", null);
            textView.setText(result);
            removeDialog(DIALOG_KEY);
        }

        // 该方法运行在UI线程当中,并且运行在UI线程当中 可以对UI空间进行设置
        @Override
        protected void onPreExecute() {
            showDialog(DIALOG_KEY);
        }

        /**
         * 这里的Intege参数对应AsyncTask中的第二个参数
         * doInBackground方法当中,,每次调用publishProgress方法都会触发onProgressUpdate执行
         * onProgressUpdate是在UI线程中执行,所有可以对UI空间进行操作
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值