在HTML响应Java中仅定位和提取特定标记
我正在尝试使用网站“”查找名称的性别。我能够使用get-request传递参数,并获得html页面作为响应,如下所示在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
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
- 寻找稀有元素
- 寻找独特的文本