玩爬蟲的時候,如果訪問的太頻繁的話,很容易被封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)即可