gpt4 book ai didi

java - 无法使用 Jsoup 从网站上抓取价格

转载 作者:行者123 更新时间:2023-11-30 01:49:03 27 4
gpt4 key购买 nike

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

最佳答案

这是因为您获取的是 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

关于java - 无法使用 Jsoup 从网站上抓取价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56778407/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com