一日一技:如何捅穿Cloud Flare的5秒盾
經(jīng)常寫爬蟲的同學(xué),肯定知道 Cloud Flare 的五秒盾。當(dāng)你沒有使用正常的瀏覽器訪問網(wǎng)站的時候,它會返回如下這段文字:
- Checking your browser before accessing xxx.
- This process is automatic. Your browser will redirect to your requested content shortly.
- Please allow up to 5 seconds…
即使你把 Headers 帶完整,使用代理 IP,也會被它發(fā)現(xiàn)。我們來看一個例子。Mountain View Whisman students sent home after children test positive for COVID-19 [1] 這篇文章,使用正常瀏覽器訪問,效果如下圖所示:
直接查看原始的網(wǎng)頁源代碼,可以看到,新聞標(biāo)題和正文就在源代碼里面,說明新聞的標(biāo)題和正文都是后端渲染的,不是異步加載。如下圖所示:
現(xiàn)在,我們使用 requests,帶上完整的請求頭來訪問這個網(wǎng)站,效果如下圖所示:
網(wǎng)站識別到了爬蟲行為,成功把爬蟲請求擋住了。很多同學(xué)在這個時候就已經(jīng)束手無策了。因為這是爬蟲的第一次請求就被擋住了,所以網(wǎng)站不是檢測的 IP 或者訪問頻率,所以即使用代理 IP 也無濟于事。而現(xiàn)在即使帶上了完整的請求頭都能被發(fā)現(xiàn),那還有什么辦法繞過這個檢測呢?
實際上,要繞過這個5秒盾非常簡單,只需要使用一個第三方庫,叫做cloudscraper。我們可以使用pip來安裝:
- python3 -m pip install cloudscraper
安裝完成以后,只需要使用3行代碼就能繞過 Cloud Flare 的5秒盾:
- import cloudscraper
- scraper = cloudscraper.create_scraper()
- resp = scraper.get('目標(biāo)網(wǎng)站').text
我們還是以上面的網(wǎng)站為例:
- import cloudscraper
- from lxml.html import fromstring
- scraper = cloudscraper.create_scraper()
- resp = scraper.get('https://mv-voice.com/news/2021/05/04/mountain-view-whisman-students-sent-home-after-children-test-positive-for-covid-19').text
- selector = fromstring(resp)
- title = selector.xpath('//h1/text()')[0]
- print(title)
運行效果如下圖所示:
破盾成功。
CloudScraper[2] 非常強大,它可以突破 Cloud Flare 免費版各個版本的五秒盾。而且它的接口和 requests 保持一致。原來用 requests 怎么寫代碼,現(xiàn)在只需要把requests.xxx改成scraper.xxx就可以了。
參考資料
[1]Mountain View Whisman students sent home after children test positive for COVID-19 : https://mv-voice.com/news/2021/05/04/mountain-view-whisman-students-sent-home-after-children-test-positive-for-covid-19
[2]CloudScraper: https://github.com/venomous/cloudscraper
本文轉(zhuǎn)載自微信公眾號「未聞Code」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系未聞Code公眾號。