android - 如何从获取响应中提取特定的 <div> 标签?

标签 android dom httprequest

我发出了一个 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/

相关文章:

android - FCM 后台同步失败 : AUTHENTICATION_FAILED

Java:如何在 org.w3c.dom 中用 <sometag> 包装所有元素?

android - 导航 View android中的标题重复

android - StableArrayAdapter 与 ArrayAdapter

android - 我可以为 ACTION_MEDIA_SCANNER_SCAN_FILE Intent 使用什么权限?

jquery - 拖放日历

javascript - jQuery append() 不适用于某些元素

java - 我应该使用多线程吗

c++ - 网络爬虫在 read() 中下载网页的 recv 缓冲区应该有多大?

http - 服务器不响应手动请求