方法一(仅适用于小型网站):
提供加密/编码数据。
我使用Python(urllib、requests、beautifulSoup等)扫描网络,并发现许多网站提供加密/编码数据,这些数据在任何编程语言中都无法解密,因为加密方法不存在。
我在PHP网站中实现了这一点,通过对输出进行加密和最小化处理(警告:对于大型网站来说,这不是一个好主意),响应总是混乱的内容。
以下是在PHP中最小化输出的示例(如何最小化PHP页面HTML输出?):
<?php
function sanitize_output($buffer) {
$search = array(
'/\>[^\S ]+/s',
'/[^\S ]+\</s',
'/(\s)+/s'
);
$replace = array('>', '<', '\\1');
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
ob_start("sanitize_output");
?>
方法二:
如果您无法阻止爬虫,可以提供伪造的/无用的数据作为响应。
方法三:
阻止常见的爬虫用户代理,大型网站通常会采取此方法,使用“python3.4”等User-Agent无法对其进行爬取。
方法四:
确保所有用户标头都是有效的。我有时会提供尽可能多的标头来使我的爬虫看起来像一个真实的用户,其中一些甚至不是真实或有效的,比如 en-FU :)。这是我通常提供的一些标头列表。
headers = {
"Requested-URI": "/example",
"Request-Method": "GET",
"Remote-IP-Address": "656.787.909.121",
"Remote-IP-Port": "69696",
"Protocol-version": "HTTP/1.1",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip,deflate",
"Accept-Language": "en-FU,en;q=0.8",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"Dnt": "1",
"Host": "http://example.com",
"Referer": "http://example.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"
}