无法使用 Jsoup 从网站上获取价格

我在大学里有一个项目,我需要构建一个软件来根据用户应输入的 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


UYOU
浏览 132回答 1
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");
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java