Jsoup遍历Elements会导致重复输出

时间:2015-04-23 07:32:16

标签: java for-loop jsoup element elements

我有一个页面链接从中提取一些数据(我想得到表格和一些tds属性)。 This image as a source sample

我使用for循环来迭代通过我必须提取一些属性的元素 它的。但我得到了重复的输出。

输出应该与我帖子末尾图片的输出相似

Document doc = Jsoup.connect("http://www.saudisale.com/SS_a_mpg.aspx").get();
Elements elements = doc.select("table").select("tbody").select("tr").select("td") ;

for(Element e:elements) {
    System.out.println(e.select("span[id~=Label4]").text() + 
            "\t" + e.select("input[id$=ImageButton1]").attr("src") + 
            "\t" + "" + e.select("span[id~=Label13]").text());
}

这是我得到它们的输出,它们是重复的! :

enter image description here

The output should be like this:-

enter image description here

2 个答案:

答案 0 :(得分:0)

请尝试以下代码吗?

    Elements description = doc.select("tbody");
    doc=Jsoup.parse(description.html());
    description = doc.select("td");

    for(int j = 0; j < description.size(); ++ j)
    {
        String bodytext = description.eq(j).text(); // bodytext is the text of each TD
    }

答案 1 :(得分:-1)

我用for循环代替递增计数器,问题解决了。 其中31是该页面上的项目数

以下代码给出了所需的输出。

for(int i=1;i<description.size();i++)
{

System.out.println(elements.select("td").select("span[id~=Label4]").get(i).text()+""+elements.select("td").select("input[id$=ImageButton1]").get(i).attr("src"));   

}