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

时间:2019-11-24 15:34:47

标签: java 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元素中抓取价格时遇到问题。我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以执行与选择类相似的操作。在使用.select()创建的Elements对象上使用.get可以为您提供具有该名称的所有Element的列表。

例如,

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();
}
相关问题