猫史档案馆


网络爬虫如何高效采集

用户:LaicalLaical查看:0 回复:0 评论:0 创建时间:2020-10-27T17:26:40


网络爬虫需要利用爬虫程序去合法合规的采集数据,不能够影响被访服务器的正常运行和不能利用采集的数据去做其他违法用途。那么如果在爬虫程序在合法合规场景下高效率的采集数据呢?

使用代理IP:

使用IP代理池简单的说,就是通过ip代理,从不同的ip进行访问,这样就不会被封掉ip了。正常的网站服务器都会检测访问用户,如果网站检测到同一个ip在短时间之内频繁多次的向网站发出不同的HTTP请求,那么基本上就会被判定为爬虫程序,过一段时间就无法采集,所以说如果不是用代理IP是无法正常去采集的。

爬虫程序的维护:

维护爬虫程序的优化,可以规避一些反爬的机制,比如向网站发出HTTP请求时带上UA,或者保存一下cookies,这样模拟真实用户,目标服务器就不容易被检测识破。

制作完善的爬虫程序:

    import okhttp3.*;

    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.Proxy;
    import java.util.concurrent.TimeUnit;

    public class OkHttp {

        // 代理服务器(产品官网 www.16yun.cn)
        final static String proxyHost = "t.16yun.cn";
        final static Integer proxyPort = 31111;

        // 代理验证信息
        final static String proxyUser = "USERNAME";
        final static String proxyPass = "PASSWORD";

        static OkHttpClient client = null;

        static {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));

            Authenticator proxyAuthenticator = new Authenticator() {
                public Request authenticate(Route route, Response response) {
                    String credential = Credentials.basic(proxyUser, proxyPass);
                    return response.request().newBuilder()
                            .header("Proxy-Authorization", credential)
                            .build();
                }
            };

            client = new OkHttpClient().newBuilder()
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .readTimeout(5, TimeUnit.SECONDS)
                    .proxy(proxy)
                    .proxyAuthenticator(proxyAuthenticator)
                    .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))
                    .build();
        }

        public static Response doGet() throws IOException {
            // 要访问的目标页面
            String targetUrl = "http://httpbin.org/ip";

            Request request = new Request.Builder()
                    .url(targetUrl)
                    .build();
            Response response = client.newCall(request).execute();
            return response;
        }

        public static void main(String[] args) throws IOException {
            Response response1 = doGet();
            System.out.println("GET请求返回结果:");
            System.out.println(response1.body().string());
        }

    }


想要高效的采集数据,就需要一个完善的爬虫程序,爬虫程序的配置一定要稳定。一个完善的爬虫程序要有自己相应的报错机制保存,这样确保整个爬虫程序最后能够完整爬取下来。

制作爬虫程序:


回复

上一页1 页 / 共 0下一页