睡前来一发
开发一个基于Jsoup的阅读笑话应用,有点类似于糗事百科,在此做一个初级版本
我们要用Jsoup 抓取下面这个网页内容http://www.jokeji.cn/hot.htm
下面是APP展示效果
下面是进入首页
抓取的是http://www.jokeji.cn/hot.htm这个网站上的内容
代码部分
1.首页抓取
<div style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif;"> </span><pre name="code" class="java"> Runnable runnable = new Runnable(){ @Override public void run() { Message message = new Message(); try { String url = "http://www.jokeji.cn/hot.htm"; Connection conn = Jsoup.connect(url); // 修改http包中的header,伪装成浏览器进行抓取 conn.header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:32.0) Gecko/ 20100101 Firefox/32.0"); Document doc = conn.get(); // 获取tbody元素下的所有tr元素 Elements elements = doc.select("table[background=images/d01.gif]"); Log.v(TAG, "size() "+elements.size()); for(Element element : elements) { String tit =element.getElementsByTag("a").text(); System.out.println("~~~~~" + tit); //=element.getElementsByTag("a").attr("abs:href"); Elements links = element.select("a"); StringBuffer sff = new StringBuffer(); for(Element link : links) { sff.append(link.attr("abs:href")); } Log.v(TAG,"path "+sff); map=new HashMap<String,Object>(); map.put("tit",tit); Random random=new Random(); int i=random.nextInt(4); Bitmap bit=null; switch (i){ case 0: bit= BitmapFactory.decodeResource(MainActivity.this.getResources(),R.mipmap.s1); break; case 1: bit= BitmapFactory.decodeResource(MainActivity.this.getResources(), R.mipmap.s2); break; case 2: bit= BitmapFactory.decodeResource(MainActivity.this.getResources(), R.mipmap.s3); break; case 3: bit= BitmapFactory.decodeResource(MainActivity.this.getResources(), R.mipmap.s4); break; case 4: bit= BitmapFactory.decodeResource(MainActivity.this.getResources(), R.mipmap.s5); break; default: bit= BitmapFactory.decodeResource(MainActivity.this.getResources(), R.mipmap.s1); break; } map.put("path",sff.toString()); map.put("bit",bit); list_joke.add(map); } message.what = MainActivity.GUIUPDATEIDENTIFIER; }catch(Exception x){ x.printStackTrace(); } // new MyTask().execute(); handler.sendMessage(message); } };
Runnable runnable = new Runnable(){ @Override public void run() { Message message = new Message(); try { if(url.isEmpty()){ return; } String u =url; Connection conn = Jsoup.connect(u); conn.header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:32.0) Gecko/ 20100101 Firefox/32.0"); Document doc = conn.get(); Elements elements = doc.select("span[id=text110]"); Log.v(TAG,"size "+elements.size()); all=elements.toString(); message.what = WebActivity.FG; }catch(Exception x){ x.printStackTrace(); } // new MyTask().execute(); handler.sendMessage(message); } };