【问题标题】:Having problem using Jsoup to scrape website Data使用 Jsoup 抓取网站数据时遇到问题
【发布时间】:2019-11-24 15:34:47
【问题描述】:

这是网站的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 元素中抓取价格时遇到问题。我该怎么做?

【问题讨论】:

    标签: java jsoup


    【解决方案1】:

    您可以执行与选择课程类似的操作。在使用 .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();
    }
    

    【讨论】:

    • 嘿,使用字符串的描述变量有问题,所以如果我做字符串描述,我会收到一个错误,说变量已在方法中定义。
    • 哦,抱歉,我没有意识到我使用了两次描述。只需将第二个描述变量切换为任何其他变量名称,它就会起作用。我将编辑我的帖子以修复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 2013-08-11
    • 2020-10-05
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多