[英]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>
这显然位于网页中,但这里是我尝试运行此代码的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.