从网站和列表中搜索信息?

时间:2015-11-17 19:17:34

标签: android jsoup

您好我已经在这个问题上待了几天了。作为项目的一部分,我需要使用JSOUP将此eBuyer Search网站的产品名称和价格带回我的应用程序。

我想知道3个问题,在这一刻,代码将产品名称的所有h1标题和该页面上的所有价格作为一个句子返回。

  1. 有没有办法可以解析Android中的信息,一次带回一个项目并列出它,以及产品名称而不是文本块。
  2. 一旦列出了正确的信息,我将如何收听该产品的特定点击并将其存储在变量中?
  3. 非常感谢您的帮助,

    private class Title extends AsyncTask<Void, Void, Void> {
    
        String h1,h3;
    
        @Override
        protected Void doInBackground(Void... params) {
            try {
                // Connect to the web site
                Document element = Jsoup.connect("http://www.ebuyer.com/search?q=" + search ).get();
    
                h1 = element.body().getElementsByTag("h2").text();
    
                h3 = element.body().getElementsByTag("h1").text();
    
            } catch (IOException e) {
                e.printStackTrace();
    
            }
            return null;
        }
    
        @Override
        protected void onPostExecute(Void result) {
            // Set title into TextView
            TextView textView = (TextView) findViewById(R.id.textView3);
            textView.setText(h3);
    
            TextView textView2 = (TextView) findViewById(R.id.textView2);
            textView2.setText(h1);
        }
    }
    

    上面的代码是我使用JSOUP的方法

    下面的图片是我搜索产品时会发生的情况。

    enter image description here

2 个答案:

答案 0 :(得分:1)

以下是获取每种产品的标题和价格的代码

Document doc = Jsoup.connect("http://www.ebuyer.com/search?q=" + search).timeout(10000).userAgent("Mozilla/5.0").get();
Elements sections = doc.select("div.listing-product");
for (Element section : sections) {
    String title = section.select("h3.listing-product-title").text();
    String price = section.select("p.price").text();
    System.out.println("Title : " + title);
    System.out.println("Price : " + price);
}

现在使用Listview显示每个产品,当列表项单击意味着当您选择的产品时,您可以做任何您想做的事 您可以从http://www.vogella.com/tutorials/AndroidListView/article.html了解listview http://developer.android.com/guide/topics/ui/layout/listview.html

答案 1 :(得分:0)

首先,您可以微调元素的定位。在您提到的页面上,每个产品都包含在具有类listing-product的元素中。在此范围内,标题由类listing-product-title指定,而价格位于类listing-price的元素中。

其次,getElementsBy...方法返回一个Elements对象,它基本上是所有匹配的ArrayList。您应该遍历列表并单独处理每个项目。

示例:

Document element = Jsoup.connect("http://www.ebuyer.com/search?q=" + search ).get();
Elements products = element.body().getElementsByClass("listing-product");
for(Element product : products){
    String title = product.getElementsByClass("listing-product-title").text();
    String price = product.getElementsByClass("listing-product-price").text();
}

您对这些物品的处理取决于您。我会创建一个POJO类来保存您的产品数据,并将所有产品添加到ArrayList。然后,您可以使用该列表支持ListViewGridView或其他内容的适配器。

相关问题