Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在HTML响应Java中仅定位和提取特定标记_Java_Html - Fatal编程技术网

在HTML响应Java中仅定位和提取特定标记

在HTML响应Java中仅定位和提取特定标记,java,html,Java,Html,我正在尝试使用网站“”查找名称的性别。我能够使用get-request传递参数,并获得html页面作为响应,如下所示 URL url = new URL( "http://www.gpeters.com/names/baby-names.php?name=sarah"); HttpURLConnection connection = null; try { // Create connection connecti

我正在尝试使用网站“”查找名称的性别。我能够使用get-request传递参数,并获得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是女孩..

添加到项目中。使用它将HTML转换为XML。之后,您可以使用标准的XML工具(如或)来检查数据

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

  • 查找具有
    id
    属性的元素,因为它们是唯一的
  • 寻找稀有元素
  • 寻找独特的文本

如何识别此文本的位置?HTML响应页面上的标签就像是一个女孩!如果它有一个唯一的路径,那么你可以使用XPath提取你需要的文本。在这里,我必须只提取像“it's a girl”这样的字符串,我不能依赖标记,因为还有很多其他标记。是否可以通过XPath只提取字符串?