很多網(wǎng)站的防采集的辦法,就是判斷瀏覽器來源referer和cookie以及userAgent,道高一尺魔高一丈.
最近發(fā)現(xiàn)維護的一個爬蟲應(yīng)用,爬不到數(shù)據(jù)了,看了一下日志發(fā)現(xiàn)被爬網(wǎng)站做了防采集策略,經(jīng)過定位后,發(fā)現(xiàn)被爬網(wǎng)站是針對referer做了驗證,以下是解決方法:
在Java中獲取一個網(wǎng)站的HTML內(nèi)容可以通過HttpURLConnection來獲取.我們在HttpURLConnection中可以設(shè)置referer來偽造referer,輕松繞過這類防采集的網(wǎng)站:
HttpURLConnection connection = null;
URL url = new URL(urlStr);
if (useProxy) {
Proxy proxy = ProxyServerUtil.getProxy();
connection = (HttpURLConnection) url.openConnection(proxy);
} else {
connection = (HttpURLConnection) url.openConnection();
}
connection.setRequestMethod( "POST");
connection.setRequestProperty("referer", "http://xxxx.xxx.com");
connection.addRequestProperty("User-Agent", ProxyServerUtil.getUserAgent());
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!