【问题标题】:Cannot scrape price from website with Jsoup无法使用 Jsoup 从网站上抓取价格
【发布时间】:2021-06-05 00:07:57
【问题描述】:

我在大学有一个项目,我需要构建一个软件,该软件可以根据用户应输入的 URL(目前仅来自 Banggood.com)跟踪商品价格。

我刚刚开始学习如何从网站上抓取信息,所以我设法做到了,但我只是一开始就卡住了。我设法抓取商品标题,但未能成功使用商品价格。我上传了我当前的代码。

我无法从 Jsoup 网站或 Google 获取正确的信息

import java.io.IOException;
import java.util.Scanner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class ProjectLearning 
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        
        print("Please enter your item URL: ");
        String userUrl = scan.next();
        print("Give me a sec..");
        
        Document document;
        try {
            //Get Document object after parsing the html from given url.
            document = Jsoup.connect(userUrl).get();

            String title = document.title(); //Get title
            print("Item name: " + title); //Print title.
            
            //Get price
            Elements price = document.select("div#item_now_price");
        
            for (int i=0; i < price.size(); i++) 
            {
                print(price.get(i).text());
            }

        } catch (IOException e) 
        {
            e.printStackTrace();
        }
        print("There you go");
    }

    public static void print(String string) {
        System.out.println(string);
    }
}

输出:

Please enter your item URL: 
https://www.banggood.com/3018-3-Axis-Mini-DIY-CNC-Router-Standard-Spindle-Motor-Wood-Engraving-Machine-Milling-Engraver-p-1274569.html?rmmds=flashdeals&cur_warehouse=CN

Give me a sec..

Item name: 3018 3 axis mini diy cnc router standard spindle motor wood engraving machine milling engraver Sale - Banggood.com

【问题讨论】:

    标签: java jsoup


    【解决方案1】:

    这是因为你得到的元素是 id item_now_price 而不是 class

    查看您输入的 URL,带有价格的元素如下所示:

    <div class="item_now_price" oriattrmin="0" oriattrmax="0" noworiprice="149.9" oriprice="149.9" oriprice3="146.7" oriprice10="145.16" oriprice30="143.64" oriprice100="142.11">US$149.90</div>
    

    正确的选择器应该是Elements price = document.select("div.item_now_price");

    查看https://jsoup.org/cookbook/extracting-data/selector-syntax 了解有关选择器的更多信息。

    更新: 因此,我查看了您的代码,您没有将价格作为输出的原因是价格是通过另一个 Ajax 请求加载的。很遗憾,jSoup 在这里无法为您提供帮助。

    有关更多信息,请查看此答案:Fetch contents(loaded through AJAX call) of a web page

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 1970-01-01
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2020-05-28
      相关资源
      最近更新 更多