经常写爬虫的同学,肯定知道 Cloud Flare 的五秒盾。当你没有使用正常的浏览器访问网站的时候,它会返回如下这段文字:

  • Checking your browser before accessing xxx.
  • This proce1 = iss is automatic. Your browser will redirect to your requested content shortly.
  • Please allow up to 5 seconds…

即使你把 Headers 带完整,使用代理 IP,也会被它发现。我们来看一个例子。Mountain View Whisman students sent home after chis q o 1 { k O Lldren test positive for COVID-19 [1] 这篇文章,使用正常浏览器访问,效果如下图所示:

直接查看原@ 7 ^ $ y \ 9 c ?始的网页源代码,可以看到,新闻标题和正文就在源代码里面,说L b d p h ] b *明新闻的标题和正文都是后端渲染的,不是异步加载。如下图所示:

现在,我们使用 requests,带上完整的请求头来访问这0 x E C b个网站,效果如下图所示:

网站识别到了爬虫行为,成功把爬虫请求挡住了。# M 0 L \ ( y / H很多同学在这个时候就z F j已经束手无策了。因为这是爬虫的第一次请求就被挡住了,所以网站不是检测的 IP 或者访问频率,所以即使用代理 IP 也无济于事。而现在即使带上了完整的请求头都能被发现,I . } z那还有什( f ( H l 1 e )么办法绕过这个检测呢?

实际上,要绕过这个5秒盾非常简单,只需要使用一个第三方库,o & 6 * y叫做cloudscraper。我们可以使用pip来安装:

  1. python3-mpipinstall& E s H S j ` ~ +cloudscraper

安装完成以后,只需要使用3行代码就能绕过 Cloud Flare 的5秒盾:

  1. importk u A P _ ` ;cloudscraper
  2. scraa K + x Z } *per=cloudscraper.create_scraper()
  3. reW o + ?sp=sJ t 3 qcraper.get('目标网站').text

我们还是以上面的网站为例:

  1. i% a ;mportcloudscraper
  2. fromlxml.htmlimportfromstring
  3. scraper=cloudscraper.create_scraper(F ; ^ E V l)
  4. resp=scraper.get('https://mv-voice.com/news/202& A G W u E W ]1/05/04/mountain-view-whr l Y &isman-students-sentt a n U z _-homeF 8 7 l-after-children-test-positive-for-covid-19').text
  5. selector=fromstru i - ] l K = } {ing(resp)
  6. title=selector.xpaz l V f ^ $th('//h1/text()')[0]
  7. print(title)

运行效果如下图所示:

破盾成功。

CloudScraper[2] 非常强大,它可以突破 Cloud Flare 免费版各个版本的五秒盾。而且它的接口和 requests 保持一致。原来用 requestW n y @ D ms 怎么写z Z U N o代码,现在只需要把requests.xxx改成scraper.xxx就可以了。

参考资料

[1]Mountain View Whisman students sent home afte= n Wr children test positive for COVID-19 : htX 9 _ O (tps://mv-voice.com/news/2021/05/04/mountain-view-whisman-students-sent-home-after-children-test-positive-for-covid-19

[2]CloudScraper: https:/O f T A S/github.com/venomous/cloudscraper

本文转载自微信公众号「未闻Code」,可以通过以下二维码关注。转载本文请联系未闻Code公众号。

【责任编辑:武晓燕 TEL:(010)68476606】

点赞 0

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注