簡體   English   中英

Jsoup:獲取 div 中的文本

[英]Jsoup: Get texts inside divs

我在獲取以下 HTML 代碼中的文本時遇到了一些麻煩,我需要一些幫助。

<div class="itemlist">
    <ul>
        <li>
            <div class="Description">
            <h2>Item 1</h2>   // GET THIS
            <h3 title="Shipping :01-02 Nov">Shipping :01-02Nov</h3> // GET THIS
            </div>

            <div class="price" style="margin: 0px auto; display: none;">
            <span class="arial-12-88" style="display: inline;"></span>
            <div class="currency-USD arial-24-26-bold">450&nbsp;USD</div> // GET THIS
            <span class="arial-12-d0" style="display: inline;"></span>
            </div>

            <div class="button_set" style="display: flex;">
            <a href="productDetail.htm?pid=00020170918214914392zGPQW7nE06A2"><button class="learn">Learn More</button></a>
            <a href="user/orderDetails.htm?m=add&amp;pid=00020170918214914392zGPQW7nE06A2&amp;count=1&amp;fitting=">
            <button class="add">Add To Cart</button></a> // GET THIS                            
            </div>
        </li>
            next item ...           

    </ul>       
</div>

The output should be:
Item 1
Shipping :01-02Nov
450&nbsp;USD

我的方法太靜態,無法處理項目結構的變化。 因為並非每件商品都具有例如相同 ChildNumber 的價格。 唯一相同的是 div 類名。

我現在使用調試器來查找我必須調用的孩子:

Element content = doc.getElementsByClass("itemlist").first();
Node child1 = content.childNode(1);
for (Node node : child1.childNodes()) {
    try {
        Node desc = node.childNode(3);
        Node price = node.childNode(5);
        Node stock = node.childNode(7);
        // get description
        Node desc_elem = desc.childNode(1);
        Node desc_text = desc_elem.childNode(0);
        String desc_txt = ((TextNode) desc_text).text().trim();
    } catch (Exception e) {
        continue;
    }

請幫我找到一個更動態的方式。 理想的是獲取所有列表項並循環遍歷它們。 然后調用獲取div描述,div價格。 然后我就可以讀孩子的課文了。

    //select the div with the item list
    Element itemlist = doc.select("div.itemlist").first();
    // select each li element
    Elements items = itemlist.select("li");
    // for each li element select the corresponding div with item name, shipping info and price 
    for(Element e : items){
        System.out.println(e.select("div.Description h2").text());
        System.out.println(e.select("div.Description h3").text());
        System.out.println(e.select("div.currency-USD").text());
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM