我发出了一个 get 请求并将响应存储在字符串 response
中:
HttpClient client = new DefaultHttpClient();
String getURL = "some_url_with_param_values";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
String response = EntityUtils.toString(resEntityGet);
但我只对 <div>
感兴趣具有类名 <div class="product-data">
的 s 。所以,我这样做了:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
InputSource is;
builder = factory.newDocumentBuilder();
is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
NodeList list = doc.getElementsByTagName("product-data"); //I even tried: (div class="product-data)
String test = list.item(0).getNodeValue(); //Just to test it
不幸的是,它不起作用。任何帮助将不胜感激。
我的响应字符串基本上是一个 html 页面。
<!DOCTYPE html .....
<html>
<head>
//some script tags
</head>
<body>
//some tags
<div class="product-data">
//some other tags
</div>
//some tags
<div class="product-data">
//some other tags
</div>
....
</body>
</html>
最佳答案
我认为您应该尝试使用getElementsByClassName('product-data')
如果这不起作用,您可以随时检查 Jsoup ,它提供了一个库,可以轻松地从网页中提取 Html 元素
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url.toURI());
HttpResponse resp = client.execute(get);
String content = EntityUtils.toString(resp.getEntity());
Document doc = Jsoup.parse(content);
Elements ele = doc.select("div.classname");
此示例执行 Http GET,然后提取具有类“classname”的所有 Div 元素,然后您可以使用它执行您喜欢的操作
关于android - 如何从获取响应中提取特定的 <div> 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12948284/