0

我正在尝试通过使用网站“ 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 响应有一个类似“ It's a girl! ”的元素,其中所需的结果位于。我如何仅提取上面的字符串并打印输入参数是男孩还是女孩。示例:sarah 是女孩..

4

1 回答 1

0

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

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

  • 寻找具有id属性的元素,因为它们是唯一的
  • 寻找稀有的元素。
  • 寻找独特的文本
于 2013-10-18T09:18:30.497 回答