Java爬虫系列之三模拟浏览器【模块浏览OSChina网站】

来源:互联网 发布:win10系统优化固态 编辑:程序博客网 时间:2024/06/05 23:58

        第一节的学习使得我们学会使用HttpClient请求网页的基本方法;第二节进一步学习了Jsoup从网页中解析出所需要的内容。但在请求时,我们仍可能遇到目标网址没有错,但就是请求得不到响应的情况,比如OSChina、CSDN等网址,因此这里必须伪装成浏览器才可以进行正常的访问。

        模拟浏览器在代码的实现层,就是给请求加上Header,那么如何看应该封装的Header内容呢?运用浏览器自带的开发者选项功能(F12),查看Network下的目标网址对应的User-Agent即可:


        然后在代码的Header中加入User-Agent即可:

import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import java.io.IOException;public class OSChina {    public static void main(String[] args){        //创建HttpClient        CloseableHttpClient httpClient = HttpClients.createDefault();        //目标网址        String url = "http://www.oschina.net/";        //创建请求方法        HttpGet httpGet = new HttpGet(url);        //设置Header模拟浏览器行为        httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36");        try {            //发送请求,收取响应            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);            if(httpResponse.getStatusLine().getStatusCode() == 200){                //解析响应                String entity = EntityUtils.toString(httpResponse.getEntity());                System.out.println(entity);            }            EntityUtils.consume(httpResponse.getEntity());            httpResponse.close();        } catch (IOException e) {            e.printStackTrace();        }    }}


原创粉丝点击