有时候频繁的爬取第三方站点内容,会被站点的防火墙拦截,IP拉黑,所以这时候,就要用到代理IP,拉黑一个就换一个
htmlunit实用代理的方式比较简单,WebClient重载构造方法就有提供
package com.gcx.htmlunit;
import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlListItem;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class IpSearch {
public static void main(String[] args) {
//实例化web客户端 模拟指定浏览器
WebClient wc=new WebClient(BrowserVersion.FIREFOX_52,"60.2.148.253",80);
try {
//解析获取页面
HtmlPage page = wc.getPage("https://www.baidu.com");
//获取html
System.out.println("网页:"+page.asXml());
} catch (FailingHttpStatusCodeException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
wc.close();//关闭客户端,释放资源
}
}
}
运行效果和前面一样,只是速度会慢点 毕竟用了代理