爬虫的本质:模拟浏览器打开网页,获取网页中我们想要的那部分数据。
爬取之前,先要分析网页获取数据的流程。
网页采取的是post方法,对url地址请求数据。
post的内容为form表单, 表单结构如上图。
服务器接收到请求后发回的响应。
知道了流程,就可以用代码来模拟这个流程。
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("i", "快乐")
.add("doctype","json")
.build();
Request request = new Request.Builder()
.header()
.url("http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule")
.post(requestBody)
.build();
Call call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
result=response.body().string();
System.out.println(result);
}
});
OkHttpClient okHttpClient = new OkHttpClient(); 创建OkHttpClient对象
RequestBody requestBody = new FormBody.Builder() 创建表单对象,将post表单内的内容放进去,名键“i”对应的键值就是所需翻译的内容。
Request request = new Request.Builder() 创建request对象,
.header内放请求标头,用于让服务器将请求识别为来自标头所对应的浏览器。
.url内放请求网址。
.post()表示以post方式发起请求,省略或.get()都会以get方式发起请求。
.post()括号内存放需要post的内容,此处为表单数据,即前面创建的表单对象。
新建Call对象与Response对象,发起请求并接受返回结果。
返回结果以String形式赋给result,并打印或进行后续数据处理操作。