首先介绍一下这里使用的工具和获取数据的基本原理:
工具:1、HttpClient 4.5.3(解压之后将lib文件夹内的jar包导入项目即可)
2、gson-2.2.4.jar(处理json格式的数据)
原理:由于京东评论的页面是动态加载的,是通过ajax无刷新加载出来的。所以可以模仿ajax的过程来实现评论内容的加载。首先在评论页面的调试窗口找到请求评论的地址,如图所示:
上图的Request URL就是对后台请求评论数据的地址。其中productId是商品号,score表示评论的类型(好评为3 中评为2 差评为1 全部评论为0 追评为5),page是页码,pageSize是每页最多的评论数(最大为10)。
然后通过请求得到json数组的格式的数据,最后对这些数据进行就能筛选得到评论的数据。
上干货:
-
//通过get方法发送请求 -
public static void downloadPage(String path, String savePath,int headerLength) throws HttpException, IOException {//headerLength是上述图片中的callback -
HttpGet httpGet = new HttpGet(path);//path就是上述的Request URL -
httpGet.setHeader("Connection", "keep-alive"); -
httpGet.setHeader("User-A", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2"); -
CloseableHttpResponse response = httpclient.execute(httpGet); -
int statusCode = response.getStatusLine().getStatusCode(); -
HttpEntity entity = response.getEntity(); -
if (statusCode == HttpStatus.SC_OK) { -
InputStream input = null; -
//将请求后反应得到的数据写入输入流 -
input = entity.getContent(); -
BufferedReader br = new BufferedReader(new InputStreamReader(input)); -
String line = null; -
while ((line = br.readLine()) != null) { -
//把得到的不规范的json数据裁剪 -
String reqBody = line.toString().substring(headerLength+1, line.length() - 2); -
JsonParser parser = new JsonParser(); -
try { -
// 将json格式的字符串转换成json对象 -
JsonObject json = parser.parse(reqBody).getAsJsonObject(); -
// 得到键是comments的json数组,此时的json数组是键值对的数组 -
JsonArray jsonArray = json.getAsJsonArray("comments"); -
int length = jsonArray.size(); -
for (int i = 0; i < length; i++) { -
// 得到一条评论信息 -
JsonElement element = jsonArray.get(i); -
// 裁剪没用的json格式,得到评论信息 -
String midContent = element.getAsJsonObject().get("content").toString(); -
//去除文本首尾的引号 -
String content = midContent.substring(1, midContent.length() - 1); -
// 保留原文件的,在原文件的末尾继续写入输出文件 -
try { -
BufferedWriter out = new BufferedWriter(new FileWriter(savePath, true)); -
out.write(content + "\r\n"); -
out.close(); -
} catch (IOException e) { -
System.out.println(e); -
} -
}