简体   繁体   English

如何使用 Jsoup 获取 html 数据的特定子元素

[英]How to get specific sub-elements of html data using Jsoup

So I am trying to get all prices from a Html file using Jsoup.所以我试图使用 Jsoup 从 Html 文件中获取所有价格。 The simplified Html is structured something like this:简化的 Html 的结构如下:

//some html

<div class="price-point-wrap use-roundtrippricing">
    <div class="price-point-wrap-top use-roundtrippricing">


    <div class="pp-from-total use-roundtrippricing">Roundtrip</div>
    </div>
    <div class="price-point price-point-revised use-roundtrippricing">
        $509
    </div>

    <div class="fare-select-button-div">
        <input type="button" aria-describedby="sr_product_ECONOMY_123-745|1975-UA" value="Select" class="fare-select-button">
        <span class="visuallyhidden">fare for Economy  (lowest)</span>
    </div>

</div>

//some html

 <div class="price-point-wrap use-roundtrippricing">
    <div class="price-point-wrap-top use-roundtrippricing">


    <div class="pp-from-total use-roundtrippricing">Roundtrip</div>
    </div>
    <div class="price-point price-point-revised use-roundtrippricing">
        $1,046
    </div>

    <div class="fare-select-button-div">
        <input type="button" aria-describedby="sr_product_MIN-BUSINESS-OR-FIRST_123-745|1975-UA" value="Select" class="fare-select-button">
        <span class="visuallyhidden">fare for First  (2-cabin, lowest)</span>
    </div>

    <div class="pp-remaining-seats">​5 tickets left at this price​</div>
</div>

//some html

This is what I have tried so far:这是我到目前为止所尝试的:

File input = new File("Flights.html");
Document document = Jsoup.parse(input, "UTF-8", "");
Elements prices = document.getElementsByClass("price-point");
for(Element e: prices){
    System.out.println(e.toString());
}

This gives me the following result:这给了我以下结果:

<div class="price-point price-point-revised use-roundtrippricing">
    $509
</div>
<div class="price-point price-point-revised use-roundtrippricing">
    $1,046
</div>
.....

But now I only want prices like:但现在我只想要这样的价格:

509
1046

I tried regex by only keeping the digits e.toString().replaceAll("\\D+","") when printing it, this seems to work but that is not how I want to achieve it.我在打印时只保留数字e.toString().replaceAll("\\D+","")来尝试正则表达式,这似乎可行,但这不是我想要实现的方式。 How can I get only the numbers using Jsoup?如何使用 Jsoup 仅获取数字?

Thanks to the comment from @Eritrean, I needed to use e.text() instead of e.toString() which gave me感谢@Eritrean 的评论,我需要使用e.text()而不是e.toString()这给了我

$509 
$1,046

I still need to use regex like e.replaceAll("[$,]", "") to get rid of the dollar signs.我仍然需要使用像e.replaceAll("[$,]", "")这样的正则表达式来摆脱美元符号。

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

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