Java实现一个ip池,让你的蜘蛛畅行无阻

  玩爬虫的时候,如果访问的太频繁的话,很容易被封ip,一物降一物,有反爬,当然就有反反爬╰( ̄▽ ̄)╭

为了防止ip被封,就可以使用ip代理,让代理服务器帮你完成这个请求,再将请求结果返回给你,是不是很像平时我们用的梯子 ( ‵▽′)ψ ;

使用代理之后,你的每个请求都是由很多个代理服务器帮你完成.国内用的比较多的就是西刺代理,还有其他代理也不错;

下面用java实现一个ip代理池:

这里我使用的是selenium,来爬取的西刺代理,具体可以参考我上一篇文章https://blog.csdn.net/qq_27948811/article/details/96746566,如果觉得麻烦也可以自己正则去匹配西刺代理的ip和端口信息

import com.alibaba.fastjson.JSON;
import com.linchtech.linchspider.entity.po.ProxyIp;
import com.linchtech.linchspider.xigua.WebDriverPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
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.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author: 107
 * @date: 2019-09-07 18:50
 * @description:
 **/
@Component
@Slf4j
public class ProxyIpPool {

    public static ConcurrentLinkedQueue<ProxyIp> proxyIps = new ConcurrentLinkedQueue<>();


    @Scheduled(cron = "0 0/10 * * * ?")
    public void getProxy() {
        // 这里用了自己实现的一个selenium驱动池,也可以自己new一个,及时关闭就行
        WebDriverPool webDriverPool = new WebDriverPool(1);
        ChromeDriver chromeDriver = null;
        try {
            chromeDriver = webDriverPool.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        chromeDriver.get("https://www.xicidaili.com/");
        List<WebElement> elements = chromeDriver.findElements(By.xpath("//table[@id='ip_list']/tbody/tr"));
        for (int i = 2; i < elements.size(); i++) {
            WebElement element = elements.get(i);
            try {
                WebElement ipElement = element.findElement(By.xpath(".//td[2]"));
                String ip = ipElement.getText();
                WebElement portElement = element.findElement(By.xpath(".//td[3]"));
                String portStr = portElement.getText();
                WebElement annoy = element.findElement(By.xpath(".//td[4]"));
                WebElement type = element.findElement(By.xpath(".//td[6]"));
                int port = Integer.parseInt(portStr);
                ProxyIp proxyIp = new ProxyIp();
                proxyIp.setIp(ip);
                proxyIp.setPort(port);
                proxyIp.setType(type.getText());
                proxyIp.setLocation(annoy.getText());
                if (test(ip, port)) {
                    // 保存到队列
                    if (!proxyIps.contains(proxyIp)) {
                        proxyIps.add(proxyIp);
                    }
                } else {
                    proxyIps.remove(proxyIp);
                }
            } catch (Exception e) {
                continue;
            }
        }
        webDriverPool.returnToPool(chromeDriver);
        webDriverPool.closeAll();
    }

    /**
     * 从队列中获取一个可用的ip
     * @return
     */
    public ProxyIp getOneIp() {
        if (!proxyIps.isEmpty()) {
            return proxyIps.poll();
        }
        return null;
    }

    /**
     * 将ip返回到池中
     * @param proxyIp
     */
    public void returnToPool(ProxyIp proxyIp) {
        proxyIps.add(proxyIp);
    }

    /**
     * 测试代理ip是否可用
     *
     * @return
     */
    private boolean test(String ip, Integer port) {
        try {
            //创建httpClient实例
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //创建httpGet实例
            HttpGet httpGet = new HttpGet("http://www.baidu.com");
            //设置代理IP,设置连接超时时间 、 设置 请求读取数据的超时时间 、 设置从connect Manager获取Connection超时时间、
            HttpHost proxy = new HttpHost(ip, port);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setProxy(proxy)
                    .setConnectTimeout(2000)
                    .setSocketTimeout(2000)
                    .setConnectionRequestTimeout(2000)
                    .build();
            httpGet.setConfig(requestConfig);
            //设置请求头消息
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like " +
                    "Gecko) Chrome/62.0.3202.94 Safari/537.36");
            CloseableHttpResponse response = httpClient.execute(httpGet);
            if (response == null) {
                log.warn("ip:{}不可用", ip);
                return false;
            } else {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        log.warn("ip:{}不可用", ip);
        return false;
    }
}
public class ProxyIp {
   
    private Long id;

    private String ip;

    private Integer port;
    /**
     * 1http; 2 https
     */
    private String type;

    private String location;

}

这里使用ConcurrentLinkedQueue来保存可以使用的ip,使用完了再重新添加进队列,因为ConcurrentLinkedQueue是线程安全的,poll操作的时候不会出现两个任务同时使用一个ip;

从西刺代理获取到的ip和端口信息,有些不可用,所以需要测试是否能用,test()方法就是使用代理的ip和端口去访问百度,能访问通就表示可以使用,也可以记录下访问时长,将这些代理ip的访问速度排个序;

使用的时候,只需要调用

访问任务完成之后调用returnToPool(ProxyIp proxyIp)即可

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值