android 利用Jsoup抓取网站数据 报错 求大神指导~

发布于 2021-11-23 23:27:58 字数 2768 浏览 715 评论 2

package com.example.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;








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

import android.net.Uri;


import com.example.entity.Goods;

public class GoodsService {

	/**
	 * 获取优来网商城信息
	 * @return
	 * @throws IOException 
	 */
	
	public static List<Goods> getGoods() throws IOException {
		// TODO Auto-generated method stub
		String url="http://www.ulai8.com/index.php?do=goodslist";
		List<Goods> date =new ArrayList<Goods>();
		Goods goods=null;
		 Document doc=Jsoup.connect(url).timeout(5000).get();
		 
		 Document content=Jsoup.parse(doc.toString());
		 
		 System.out.println("c"+content);
		 
		Elements div=content.select("div.list-img");
		
		//System.out.println("a"+div.toString());
		Document divcontions =Jsoup.parse(div.toString());
		//获取divs中的所有li标记
		Elements elements=divcontions.select("li.list-item");
		for(Element e:elements)
		{
			goods.name =e.select("a.list-title").text();
			System.out.println("c"+goods.name);
			goods.image="http://www.ulai8.com/data/uploads/2014/12/03/210_1196045436547ef8e88b412.jpg";
			date.add(goods);
			
		}
		System.out.println("c"+date.get(1));
		
		return date;
	}

	/**
	 * 获取网络图片如果图片在缓存中  直接在缓存读取图片
	 * @param path
	 * @return
	 * @throws IOException 
	 * @throws MalformedURLException 
	 */
	public static Uri getimage(String path,File cacheDir) throws MalformedURLException, IOException {
		File localFile=new File(cacheDir, "http://www.ulai8.com/data/uploads/2014/12/03/210_1196045436547ef8e88b412.jpg");
		if(localFile.exists())
		{
			return Uri.fromFile(localFile);
		}else {
			HttpURLConnection conn =(HttpURLConnection) new URL(path).openConnection();
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("GET");
			if(conn.getResponseCode()==200)
			{
				FileOutputStream outStream= new FileOutputStream(localFile);
				InputStream inputStream=conn.getInputStream();
				byte[] buffer=new byte[1024];
				int len =0;
				while((len=inputStream.read(buffer))!=-1)
				{
					outStream.write(buffer, 0, len);	
				}
				inputStream.close();
				outStream.close();
				
				return Uri.fromFile(localFile);
			}
			
		}
		return null;
	}

}





如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

平生欢 2021-11-28 16:18:25

Document doc=Jsoup.connect(url).timeout(5000).get();

开始在这一段报错   后面没改什么代码 又换地方报错了 ,我也是醉了  求大神

情绪失控 2021-11-27 16:46:19

不能在主线程访问网络。。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文