gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:58:34 27 4
gpt4 key购买 nike

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

最佳答案

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

例如,

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();
}

关于java - 使用 Jsoup 抓取网站数据时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59019328/

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