-1

我正在尝试构建一个程序,该程序将从网站获取页面源并仅存储一段代码。

package Program;

import java.net.*;
import java.util.*;

public class Program {
public static void main(String[] args) {
    String site = "http://www.amazon.co.uk/gp/product/B00BE4OUBG/ref=s9_ri_gw_g63_ir01?pf_rd_m=A3P5ROKL5A1OLE&pf_rd_s=center-5&pf_rd_r=0GJRXWMKNC5559M5W2GB&pf_rd_t=101&pf_rd_p=394918607&pf_rd_i=468294";
    try {
        URL url = new URL(site);
        URLConnection connection = url.openConnection();
        connection.connect();
        Scanner in = new Scanner(connection.getInputStream());
        while (in.hasNextLine()) {
            System.out.println(in.nextLine());
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}
}

到目前为止,这只会在输出中显示代码。我希望程序搜索特定字符串并仅显示价格。例如

<tr id="actualPriceRow">
<td id="actualPriceLabel" class="priceBlockLabelPrice">Price:</td>
<td id="actualPriceContent"><span id="actualPriceValue"><b class="priceLarge">£599.99</b></span>
<span id="actualPriceExtraMessaging">

搜索class="priceLarge">并仅显示/存储 599.99

我知道网站上有类似的问题,但是我不太了解任何 php,并且想要一个 java 解决方案,尽管欢迎任何解决方案:)

4

2 回答 2

0

您可以使用一些库进行解析,例如。汤

Document document = Jsoup.connect("http://www.amazon.co.uk/gp/product/B00BE4OUBG/ref=s9_ri_gw_g63_ir01?pf_rd_m=A3P5ROKL5A1OLE&pf_rd_s=center-5&pf_rd_r=0GJRXWMKNC5559M5W2GB&pf_rd_t=101&pf_rd_p=394918607&pf_rd_i=468294").get();

然后你可以搜索具体元素

Elements el = document.select("b.priceLarge");

然后你可以得到这个元素的内容,比如

String content = el.val();
于 2013-06-01T19:45:32.627 回答
0

OP在问题编辑中写道:

谢谢大家的回复,这真的很有帮助,这里是答案:

package Project;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class Project {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    Document doc;
    try {
        doc = Jsoup.connect("url of link").get();
        String title = doc.title();
        System.out.println("title : " + title);
        String pricing = doc.getElementsByClass("priceLarge").text();
        String str = pricing;
        str = str.substring(1);
        System.out.println("price : " + str);
    } catch (Exception e) {
        System.out.println(e);
    }
}
}
于 2015-11-05T16:06:52.950 回答