和许多网站一样,Cloudflare也会对访问进行检测,看是否由Selenium bot发起。这种检测主要关注是否存在特有的js变量,如包含”selenium”、”webdriver”的变量,或者包含”$cdc_”、”$wdc_”的文件变量。
每个驱动程序的检测机制可能不同,以下的解决方案主要针对chromedriver。
1、使用Undetected-chromedriver 这是一个非常便利的包,可以直接通过pip进行安装。然后像下面这样初始化驱动程序,之后的操作就像常规的Selenium使用一样。
pythonCopy code
import undetected_chromedriver as uc
driver = uc.Chrome()
driver.get('https://nowsecure.nl')
2、直接修改chromedriver可执行文件 你可以将key变量更改为任意不包含”cdc”的字符。
javascriptCopy code
/**
* Returns the global object cache for the page.
* @param {Document=} opt_doc The document whose cache to retrieve. Defaults to
* the current document.
* @return {!Cache} The page's object cache.
*/
function getPageCache(opt_doc, opt_w3c) {
var doc = opt_doc || document;
var w3c = opt_w3c || false;
// |key| is a long random string, unlikely to conflict with anything else.
var key = '$cdc_asdjflasutopfhvcZLmcfl_';
if (w3c) {
if (!(key in doc))
doc[key] = new CacheWithUUID();
return doc[key];
} else {
if (!(key in doc))
doc[key] = new Cache();
return doc[key];
}
}
这两种方法在本质上没有太大的区别。实际上,undetected-chromedriver在启动chromedriver时会应用一个补丁,完成了修改key的步骤。
pythonCopy code
def patch_exe(self):
"""
Patches the ChromeDriver binary
:return: False on failure, binary name on success
"""
logger.info("patching driver executable %s" % self.executable_path)
linect = 0
replacement = self.gen_random_cdc() #这里修改了cdc的名称
with io.open(self.executable_path, "r+b") as fh:
for line in iter(lambda: fh.readline(), b""):
if b"cdc_" in line:
fh.seek(-len(line), 1)
newline = re.sub(b"cdc_.{22}", replacement, line)
fh.write(newline)
linect += 1
3、使用穿云API,您可以轻松地绕过Cloudflare的机器人验证,即使您需要发送10万个请求,也不必担心被识别为抓取者。
一个穿云API即可突破所有反Anti-bot机器人检查,轻松绕过Cloudflare、CAPTCHA验证,WAF,CC防护,并提供了HTTP API和Proxy,包括接口地址、请求参数、返回处理;以及设置Referer,浏览器UA和headless状态等各浏览器指纹设备特征。
