使用 Jsoup 抓取网站数据时遇到问题



这是网站的html代码:

<div class="list_item">
<a href="/p/fifa-19-ps4" title="Fifa 19... on PS4">
<img src="/uploads/products/42376/42376_xsm.jpg?v=MjAxOS0xMS0yNCAxNToxMjowMw==" alt="Fifa 19... on PS4" title="Fifa 19... on PS4" border="0">
<div class="product_name">Fifa 19...</div>
<span>£9.99</span>
</a>
<a href="/p/fifa-19-ps4" class="button in_stock" title="Fifa 19 on PS4">View Product</a>
</div>

我使用 JSoup 的代码:

Document doc = Jsoup.connect("https://www.simplygames.com/search?keywords=" + itemName).get();
//Get all products on the page
Elements products = doc.select("list_item");
//work through the products using for loop
for(int i = 0; i<products.size(); ++i){
//get the product description
Elements description = products.get(i).select("product_name");
//get the products price
Elements price = products.get(i).select("");
//Ouput web scraped data
System.out.println("DESCRIPTION: " + description.text() + "; PRICE:  " + price.text());

}

我在从没有像div 这样的类的 span 元素中抓取价格时遇到问题。我该怎么做?

您可以执行与选择类类似的操作。在用 .select(( 创建的 Elements 对象上使用 .get 会给你一个具有该名称的所有元素的列表。

例如

Elements description = products.get(i).select("product_name");

此行为您提供了页面上类名为"product_name"的所有Element

您要做的是对"product_name"组中的每个元素运行另一个选择。

for (Element e : description) {
String desc = e.ownText();
String price = e.selectFirst("span").text();
}

最新更新