簡體   English   中英

使用Jsoup從網頁獲取價格

[英]Get price from webpage using Jsoup

我正在嘗試從網頁上的產品中獲取價格。 特別是從以下html內部。 我不知道如何使用CSS,但是到目前為止,這是我的嘗試。

 <div class="pd-price grid-100"> <!-- Selling Price --> <div class="met-product-price v-spacing-small" data-met-type="regular"> <span class="primary-font jumbo strong art-pd-price"> <sup class="dollar-symbol" itemprop="PriceCurrency" content="USD">$</sup> 399.00</span> <span itemprop="price" content="399.00"></span> </div> </div> 

> $ 399.00

這顯然位於網頁中,但這里是我嘗試運行此代碼的Java代碼。

  String url ="https://www.lowes.com/pd/GE-700-sq-ft-Window-Air-Conditioner-115-Volt-14000-BTU-ENERGY-STAR/1000380463"; Document document = Jsoup.connect(url).timeout(0).get(); String price = document.select("div.pd-price").text(); String title = document.title(); //Get title System.out.println(" Title: " + title); //Print title. System.out.println(price); 
Element priceDiv = document.select("div.pd-price").first();
String price = priceDiv.select("span").last().attr("content");

如果您也需要貨幣:

String priceWithCurrency = priceDiv.select("sup").text();

我沒有運行這些,但應該可以。 有關更多詳細信息,請參見JSoup API參考。

首先,您應該熟悉CSS選擇器

W3School有一些資源可以幫助您入門。

在這種情況下,您需要的東西位於帶有pd-price類的div ,因此div.pd-price已經正確。

您需要先獲取元素。

Element outerDiv = document.selectFirst("div.pd-price");

然后使用另一個選擇器獲得子div

Element innerDiv = outerDiv.selectFirst("div.met-product-price");

然后在其中獲取span元素

Element spanElement = innerDiv.selectFirst("span.art-pd-price");

此時,您可以獲取<sup>元素,但是在這種情況下,您可以只調用text()方法來獲取文本

System.out.println(spanElement.text());

這將打印

$ 399.0

編輯:看到其他答案中的評論后

您可以從瀏覽器獲取cookie,然后從Jsoup發送它以繞過郵政編碼要求

Document document = Jsoup.connect("https://www.lowes.com/pd/GE-700-sq-ft-Window-Air-Conditioner-115-Volt-14000-BTU-ENERGY-STAR/1000380463")
                        .header("Cookie", "<Your Cookie here>")
                        .get();

暫無
暫無

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

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