Android中用Jsoup解析Snapdeal页面数据填充RecyclerView遇阻
解决Jsoup解析Snapdeal页面提取商品数据的问题
看起来你已经搭好了基础的网络请求和LiveData框架,现在卡在Jsoup解析HTML提取数据这一步,我来帮你一步步解决这个问题。
先修正两个基础错误
- 获取HTML内容的方式错误:你现在用
responseBodyResponse.body().toString(),这得到的是OkHttpResponseBody对象的字符串标识,不是实际的HTML源码。应该改成responseBodyResponse.body().string()来获取真实的HTML内容。 - 选择器语法错误:
product-tuple-image是元素的class属性,Jsoup里选择class需要在前面加.,也就是.product-tuple-image,否则会被当成标签名来查找,自然找不到元素。
步骤1:创建商品数据类
首先,我们需要一个数据类来存储提取到的商品信息,方便后续传入RecyclerView的Adapter:
// 用Java Bean存储商品信息 public class Product { private String imageUrl; private String name; private String price; public Product(String imageUrl, String name, String price) { this.imageUrl = imageUrl; this.name = name; this.price = price; } // Getter方法 public String getImageUrl() { return imageUrl; } public String getName() { return name; } public String getPrice() { return price; } }
步骤2:正确解析HTML提取数据
接下来,我们需要分析Snapdeal页面的HTML结构(你可以打开目标网址,右键检查元素查看):
- 每个商品项的容器通常是带有
product-tuple-listing类的元素 - 商品图片在
.product-tuple-image下的img标签,优先取data-src属性(网站常用懒加载存储真实地址),没有的话再取src - 商品名称在
.product-title类的元素里 - 商品价格在
.product-price类的元素里
下面是修正后的完整解析代码:
private void observeLiveData () { snapdealViewModel.searchProduct("watch", "plrty").observe(this, new Observer<Response<ResponseBody>>() { @Override public void onChanged(@Nullable Response<ResponseBody> responseBodyResponse) { try { // 修正:获取真实的HTML内容 String html = responseBodyResponse.body().string(); Document document = Jsoup.parse(html); // 选择所有商品项的容器 Elements productItems = document.select(".product-tuple-listing"); List<Product> productList = new ArrayList<>(); for (Element item : productItems) { // 提取商品图片地址 String imageUrl = item.select(".product-tuple-image img").attr("data-src"); if (imageUrl.isEmpty()) { imageUrl = item.select(".product-tuple-image img").attr("src"); } // 提取商品名称 String productName = item.select(".product-title").text().trim(); // 提取商品价格 String productPrice = item.select(".product-price").text().trim(); // 过滤无效数据,添加到列表 if (!imageUrl.isEmpty() && !productName.isEmpty()) { productList.add(new Product(imageUrl, productName, productPrice)); } } // 这里将数据传给RecyclerView的Adapter // 示例:yourProductAdapter.setProductList(productList); // yourProductAdapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); // 不要吞掉异常,方便调试定位问题 } } }); }
关键注意事项
- 网站结构可能变化:电商网站的HTML结构随时可能调整,如果后续解析失效,记得重新打开网页检查元素,更新选择器。
- 图片加载优化:RecyclerView里加载网络图片建议用Glide或Picasso库,直接用ImageView加载会有性能问题。
- 权限检查:确保你的AndroidManifest.xml里添加了网络权限:
<uses-permission android:name="android.permission.INTERNET" />
内容的提问来源于stack exchange,提问作者karthik kolanji
相关产品推荐
相关产品推荐

