简体   繁体   English

为什么getElementsByClass在jsoup中不起作用?

[英]Why getElementsByClass does not work in jsoup?

I am trying to get some elements by their class names. 我试图通过类名来获取一些元素。 Here is the HTML file: 这是HTML文件:

<div id="container">
    <div id="page_clips">
        <div id="content" class="margin-right-5">
            <div class="product-grid margin-left-5">
                <div>.....</div>
                <div>.....</div>
                <div>.....</div>
             </div>
        </div>
    </div>
</div>

Here, what i want to get is, the div that has the class="product-grid margin-left-5". 在这里,我想得到的是具有class =“ product-grid margin-left-5”的div。 Here is what i do: 这是我的工作:

Document doc = Jsoup.connect(link).get();
Element page_clips = doc.getElementById("page_clips");
Element page_clip_content = page_clips.getElementById("content");

This piece of code succesfully gets the div with the id "content". 这段代码成功获取了ID为“ content”的div。 Then when i try, 然后当我尝试时

Elements elementsIWantToGet= page_clip_content.getElementsByClass("product-grid margin-left-5");

it returns empty. 它返回空。 What am i doing wrong? 我究竟做错了什么? Isn't the name of the class attribute of that div is "product-grid margin-left-5" ? 该div的class属性的名称不是“ product-grid margin-left-5”吗? Can anyone help? 有人可以帮忙吗?

Thanks 谢谢

Because getElementsByClass doesn't support multiple class names. 因为getElementsByClass不支持多个类名。 By giving it "product-grid margin-left-5" , do you mean to find all elements with both classes? 通过给它"product-grid margin-left-5" ,您是要找到两个类的所有元素吗? Or either class? 还是任何一类?

Either way, use select , which accepts CSS selectors: 无论哪种方式,都可以使用select ,它接受CSS选择器:

For elements with both : 对于同时具有两个元素的元素:

.. = page_clip_content.select(".product-grid.margin-left-5");

For elements with either : 对于具有以下任一元素的元素:

.. = page_clip_content.select(".product-grid, .margin-left-5");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM