在HTML响应Java中仅查找并提取特定标记

时间:2013-10-16 15:26:08

标签: java html

我试图通过使用网站“http://www.gpeters.com/names/baby-names.php”来查找名称的性别。我能够使用get请求传递参数并获取html页面作为响应,如下所示

    URL url = new URL(
            "http://www.gpeters.com/names/baby-names.php?name=sarah");
    HttpURLConnection connection = null;
    try {
        // Create connection

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();

        // Get Response
        InputStream is = connection.getInputStream();
        int status = connection.getResponseCode();
        //System.out.println(status);

        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
        rd.close();

     //program prints whole HTML page as response.

HTML响应有一个元素,如“这是一个女孩!”,其中所需的结果位于此。如何仅提取上述字符串并打印输入参数是男孩还是女孩。示例:莎拉是个女孩..

1 个答案:

答案 0 :(得分:0)

jtidy添加到您的项目中。使用它将HTML转换为XML。之后,您可以使用JDOM 2Jaxen等标准XML工具来检查数据。

您需要做的是查看HTML代码并确定一个允许您识别所需元素的唯一路径。这里没有简单的解决方案。但有些指示:

  • 查找具有id属性的元素,因为它们是唯一的
  • 寻找罕见的元素。
  • 寻找独特的文字
相关问题