Python Selenium绕过Cloudflare抓取网页

本文介绍了如何使用Python的Selenium库绕过Cloudflare的检测机制。主要提供了两种方法:一是利用undetected-chromedriver包,二是直接修改chromedriver可执行文件中的特定变量。这些方法帮助Selenium在不被识别为bot的情况下正常访问网站。

Cloudflare和很多其他网站一样会检测访问是否为Selenium bot,其中一项为检测Selenium运行时出现的特有js变量。

这里主要包括了是否含有"selenium"/ "webdriver"的变量或者含有"$cdc_"/"$wdc_"的文件变量。

每个driver的检测机制会不一样,此处给出的方案基于chromedriver。

1. Undetected-chromedriver

非常简单好用的包,直接pip安装,如下初始化driver即可,之后就像正常Selenium使用即可。

import undetected_chromedriver as uc
driver = uc.Chrome()
driver.get('https://nowsecure.nl')

2. 直接修改chromedriver executable

将key变量修改成任意不含"cdc"的字符。

/**
 * 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的那一步

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
        return linect

*具体可参考这篇stackoverflow文章

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值