在JSoup

时间:2017-05-18 12:26:04

标签: jsoup

我有以下HTML,我希望能够使用JSoup从片段中提取汽车的名称和数量

<div class="user-info clearfix">
    <div class="user-review-name clearfix">
        <a class="user-review-name-link" rel="nofollow" title="go to tom&#39;s profile">
            tom
        </a>
    </div>
    <div class="clearfix">
        2 cars
    </div> 

我可以将名称确定,但我无法获得clearfix类中的内容。这是我的代码。

        Elements reviews = doc.select("div.review");
        for (Element review : reviews) {
            Elements subreviews = review.select("div.user-info");
            for (Element subreview : subreviews) {
                System.out.println(subreview.select("a.user-review-name-link").text());
                System.out.println(subreview.select("div:not(.user-review-name-link)").text());
            }
        }

我尝试了不同的组合,但由于某些原因,我自己永远无法获得 2辆汽车。帮助

System.out.println(subreview.select("div.clearfix").text());

我原本以为这也会起作用,但它产生了这种格式&#34; tom 2 cars tom 2 cars&#34;

1 个答案:

答案 0 :(得分:1)

你可以这样做:

final StringBuffer buff = new StringBuffer();
Elements result = doc.select("div.clearfix");

    result.traverse(new NodeVisitor() {
        public void head(Node node, int depth) {
          // DEBUG:  System.out.println("Entering tag: " + node.nodeName());
            if(node instanceof TextNode) {
                buff.append(((TextNode) node).text());
            }
        }
        public void tail(Node node, int depth) {
            //Nothing to see here
        }
    });

然后在这里打印buff的内容。

相关问题