Перейти к содержимому

Как в python обойти cloudflare

  • автор:

How to Bypass Cloudflare Detection with Selenium

Are you looking for a way to bypass Cloudflare detection when coding your bot in Python? Then you are on the right page. The article below provides a guide on how to bypass Cloudflare using Python and Selenium.

Web bots, including web scrapers, have advanced a lot over the years. And let’s face it; websites are also becoming smarter at detecting bot traffic. One of the game changers that make bot developers sweat is the Cloudflare anti-bot systems.

It acts as a middleware or a proxy between web servers and client software. If you send a web request, it will have to check to make that it is non-spam and legitimate before it will allow it to pass through to your target website.

Regular Internet users experience a little delay and get the “checking your browser before accessing ….” message on the screen. But this will eventually pass. However, if you are using a bot, you will most likely not be allowed access. Some developers think using a browser automator like Selenium would do the magic for them too.

Unfortunately, Cloudflare is built to detect such too. So what do you do, and how do you bypass Cloudflare detection as a bot developer using Python and Cloudflare? In this article, you will be shown how to bypass Cloudflare detection using Python and Selenium.

An Overview of Selenium

Selenium Overview

Selenium web driver is a browser automator. What you do with that is up to you. Some use it for site testing, others for botting and scraping. It is a versatile tool, as you can use it in multiple popular programming languages such as Python, Java, and NodeJS.

It also does support popular browsers such as Chrome, Firefox, Edge, and Internet Explorer. Our focus here is on its Python support. In Python, Selenium is the major tool for botting and scraping websites that depend on JavaScript rendering. The likes of Scrapy, Requests, and Beautifulsoup are not suited for such.

However, Selenium is only effective against websites with basic anti-spam systems. With the help of proxies, clearing cookies, setting random delays, and a few other methods, you are able to evade detection and block.

But when a website is protected by anti-spam systems like Cloudflare and Akamai, Selenium becomes ineffective. This is because there are default pointers that anti-spam systems use to detect bots that the default Selenium tool has.

How to Bypass Cloudflare Using Selenium and Python

With the right steps, Selenium can bypass Cloudflare easily. Before going into that, let’s take a look at how well Cloudflare works in detecting bots coded with Python and Selenium. To do this, we will code a simple bot that tries to access rayobyte.com.

Rayobyte overview

Rayobyte is a proxy provider protected by Cloudflare. If you try accessing it with a browser, your browser needs to be checked before you will be granted access. We’ll use this to test out how effective Cloudflare is and then code another bot that will incorporate measures to bypass it.

Step 1: Install Necessary Tools

For you to code a bot in Python, you need to have Python installed. For this project, you also need to have Selenium installed.

Python

Python Overview

For most systems, Python is already installed. However, the version installed is Python 2, which is used for legacy reasons. You will need to install Python 3 to use Selenium. Visit the official download page of Python to have it installed on your system. It is available for Windows, macOS, and Linux. To verify if the installation was done successfully, run the command below in your command prompt.

Selenium

Selenium tools

Selenium is a complete botting tool. It automates the browser, allowing you to access pages, click buttons, scroll, and even fill forms and carry out any action you can carry out manually. Selenium is a third-party tool.

For it to work, you will need to have it installed and then download and place the specific driver for the browser you want to automate in path.

For this guide, we will be using Chrome since it is the most popular browser out there.

To install Selenium, run the

command in the command prompt. Once the download is complete, you can now visit the download page for Chrome web driver. C

heck the version of Chrome you have and download the driver specifically for your Chrome version. If you download that of another version, it will not work.

Once downloaded, unzip the content in a folder. That folder will be the work folder for this project.

Step 2: Send Request to Website without Bypass Trick

Our target website is rayobyte.com. We’ll code a script that will send a request to this website and see the response we get.

Below is the code. It is quite simple. The one that requires more lines of code is actually the one with the code to bypass Cloudflare.

Use the code below in your favourite Python IDLE. In my case, I am using Pycharm, which is currently the best IDLE in the market — this is disputable though. The major problem with it is that it is paid.

The code above will launch the Chrome browser on your system and will try to access the Rayobyte website homepage.

However, instead of accessing the page, it will just be looping and remain on the Cloudflare verification page. Below is a screenshot of what the page looks like.

If you check the code well, you will see that I didn’t close it. This is to enable me to see if it will end up allowing the page to load. But that will never happen. You should close the automated browser.

As you have already seen, Selenium, by itself alone, can’t be used to bypass Cloudflare. If you want to bypass Cloudflare, you must make use of some tricks. The next step will show you how to use the same Selenium and Python to bypass Cloudflare.

Step 3: Using Plugin to Bypass Cloudflare

using Plugin to Bypass Cloudflare

As you can see from the above, Cloudflare detects Selenium scripts as bots. Using proxies will not help you in this case. You need other methods.

The best way to bypass Cloudflare with Selenium and python is to use a library known as Undetected ChromeDriver. You can install this using the

This plugin only works if you want to drive/automate Chrome. Currently, there are no options for automating other browsers. If you have this library installed, all you have to do is replace the default browser class in Selenium with this, and you are good to go.

Below is a code snippet showing you how to correctly use the Undetected ChromeDriver to bypass Cloudflare.

By just using the undetected-chromedriver library, you will see that you are able to evade detection by Cloudflare. This will enable you to automate your tasks or even scrape the web for data with no issues.

Place of Proxies for Bypassing Cloudflare

Place of Proxies for Bypassing Cloudflare

If you look at the code above, you will see that proxies were not used in the whole process. You now begin to wonder if you need proxies to bypass Cloudflare. The reason for this is simple — we only send one request. If you only need to send a few requests, you do not need to make use of a proxy to do that.

However, if you will be sending many requests as most bots do, then you need to make use of proxies.

This is because, as with most anti-bot systems, IP tracking is still one of the major parts of the Cloudflare service. And when it gets too many requests from the same IP, it does not matter whether there is a bot footprint or not; such IP will be regarded as suspicious, and as such, further requests will be blocked.

We recommend you make use of residential proxies to bypass Cloudflare. Some of the best proxy providers for these include Bright Data, Smartproxy, and Soax. If you don’t need to maintain sessions, using rotating proxies from these providers is the best for bypassing Cloudflare.

FAQs

Q. Do Proxies Protect Against Cloudflare Blockage?

No, they do not. You might see some proxies market themselves as proxies to bypass Cloudflare. The reality on the ground is the contrary. Proxies alone will not protect you against Cloudflare blockage. You need to make use of tools that can mimic regular user browsers, and that is where using the undetected ChromeDriver comes in.

Proxies are required when you need to send many requests via Cloudflare, and not using proxies risk tripping off their IP tracking and blocking system. Proxies are needed in many cases, but they are not the sole tools you need to evade Cloudflare bypass.

Q. How Effective is Cloudflare at Preventing Bots?

If your target website has Cloudflare protecting it, then you really need to be worried. This is because Cloudflare has some interesting numbers that will scare you aware without even trying to bypass them.

According to data available, websites protected by Cloudflare notice a 65 percent reduction in requests before setting up Cloudflare. This is some great work Cloudflare is doing right there. It also helps websites load faster and use less bandwidth. However, with the right techniques and tools, you can still bypass it and make it less effective.

Q. Is It Legal to Bypass Cloudflare Detection?

Anti-bot systems like Cloudflare protect websites from DDoS attacks and other forms of spam. Bypassing them is not illegal, even though websites configure them to protect their systems and databases.

However, what you do after bypassing them could put you in legal trouble. If you only need to automate your tasks without causing any harm to the website by overwhelming it with requests, then you are still within the legal frame.

We are not competent legal advisers, and as such, we recommend you seek legal advice from competent practitioners. Nothing you read here should be seen or taken as legal advice.

Conclusion

As a bot developer, anti-bot systems like Cloudflare are some of the nightmares you are going to be dealing it, as they can frustrate you. This is especially true if you do not have experience bypassing them.

As a beginner, you might think using Selenium is an easy way out for you since Selenium automates browsers and renders JS.

However, Cloudflare seems to have gotten hold of Selenium-based bots. With the help of the undetected ChromeDriver tool described in the article, you should be able to bypass it with no issues.

Python. Веб-бот VS CloudFlare (WebScrapping) [2]

На прошлом уроке вы познакомились с Selenium на практике, и сделали автоматизированного бота для накрутки лайков. В этом уроке вы научитесь обходить защиту cloudflare.

Цель.

Создать бота, который заходит на tf2.tm, и парсит цены на предметы.

Пишем бота

Для начала, попробуйте написать бота заходящего на этот сайт. Вы увидите следующую картину.

При загрузке страницы вылезает окно cloudflare, которое не даст пройти на сайт. Причина этому проста, браузер сам говорит сайту что он бот, исправим это, изменив один параметр.

Теперь попробуйте запустить бота.

Прогресс. Двигаемся дальше.

Теперь нужно дождаться загрузки предмета на странице. Для этого нам понадобятся ожидания. Для работы с ожиданиями нам потребуются импортировать следующие библиотеки.

Далее, перепишите данный код:

У WebDriverWait в функции until, указывается тип ожидания. В нашем случае это ec.visibility_of_element_located, ждем появления элемента. Ждать его мы будем 60 секунд (как и указали в WebDriverWait), если за это время элемент не появится, вызовется исключение. Элемент мы ищем с помощью css-селектора (By.CSS_SELECTOR).

Узнать об остальных типах ожидания можно в документации в графе Expected Conditions.

Теперь, соберем названия предметов и его цену, и выведем все это на экран.

Похожий код я разбирал в предыдущем уроке. В итоге мы получили список цен предметов.

Заключение.

Теперь мы можем парсить любые сайты, где для доступа к информации не требуется авторизация. И это проблема, о сохранении куки браузера и последующей его загрузке, мы поговорим на следующем уроке.

How to bypass cloudflare bot protection in selenium?

Cloudflare is a popular security service that protects websites from various threats such as DDoS attacks, bots and scraping. However, when automating website scraping or testing with Selenium, it may be challenging to bypass Cloudflare's bot protection and access the actual website content. In this tutorial, we will discuss the different methods to bypass Cloudflare's bot protection in Selenium.

Method 1: Using a headless browser

Here are the steps to bypass Cloudflare bot protection in Selenium with Python using a headless browser:

FlareSolverr Guide: Bypassing Cloudflare Made Simple

FlareSolverr is a Python package designed to help you bypass Cloudflare's anti-bot protection.

In this guide we're going to walk through how to setup and use Scrapy Splash, including:

For other method of bypassing Cloudflare then check out our How to Bypass Cloudflare guide.

Cloudflare is continously changing and upgrading their anti-bot protection systems, making it harder for web scrapers and libraries like FlareSolverr to bypass their detection methods. As a result, open source anti-bot bypassing libraries like FlareSolverr can often go out of date and stop working.

Need help scraping the web?

Then check out ScrapeOps, the complete toolkit for web scraping.

What Is FlareSolverr?​

FlareSolverr is a proxy server that you can use to bypass Cloudflare's anti-bot protection so you can scrape data from websites who have deployed their content on Cloudflare's CDN.

Cloudflare allows your scrapers to bypass Cloudflare's anti-bot pages like the one below:

Cloudflare uses numerous browser fingerprinting challenges & checks (more detail here) to determine if a request is coming from a real user or a scraper/bot.

When run, FlareSolverr starts a server that uses Python Selenium with undetected-chromedriver to solve Cloudflares Javascript and browser fingerprinting challenges by impersonating a real web browser.

FlareSolverr opens the target URL with a Selenium browser and waits until the Cloudflare challenge is solved, before returning the HTML and cookies Cloudflare returns to the browser.

You can then use these cookies to bypass Cloudflare using other HTTP clients like Python Requests.

How To Install Docker​

As the easiest way to setup FlareSolverr is using Docker (as it already contains the Chromium browser), in this guide we will first show you how to install Docker.

So if you haven't Docker installed already then use one of the following links to install Docker:

Download the Docker installation package, and follow the instructions. Your computer may need to restart after installation.

After installation, if Docker isn't running then click the Docker Desktop icon. You can check that docker is by running the command in your command line:

If it is recognized then you should be good to go.

Install & Run FlareSolverr​

Next we need to get FlareSolverr up and running.

1. Download FlareSolver​

First we need to download the FlareSolverr Docker image, which we can do by running the following command on Windows or Max OS:

Or on a Linux machine:

If everything has worked correctly, when you open you Docker Desktop on the Images tab you should see the flaresolverr/flaresolverr image (or ghcr.io/flaresolverr/flaresolverr image depending on which option you used).

Python Web Scraping Playbook - FlareSolverr Docker Desktop Installed

2. Run FlareSolverr​

To run FlareSolverr, we need to run the following command in our command line again.

For Windows and Max OS:

To check that FlareSolverr is running correctly, go to http://localhost:8191/ and you should see get a response like this.

If you do then, the FlareSolverr server is up and running correctly.

Use FlareSolverr With Our Scrapers​

When running, FlareSolverr provides a simple HTTP server that we can send the urls we want to scrape to it, and FlareSolverr will send the request via a Selenium browser and undetected-chromedriver to solve the Cloudflare challenge and return the HTML response and the cookies.

Here is a example of using FlareSolverr to scrape PetsAtHome.com a Cloudflare protected website:

Here is the same example using Python Requests instead of cURL to send the request to FlareSolverr:

The response should look something like this:

As you can see FlareSolverr has successfully solved the Cloudflare challenge "message": "Challenge solved!" and returned the cookies and HTML response from the website.

This functionality gives us two ways to use FlareSolverr:

  • Option 1: Send all requests via FlareSolverr and leave it deal with any Cloudflare challenges.
  • Option 2: Use FlareSolverr to retrieve valid Cloudflare cookies that we can then use with other HTTP clients like Python Requests.

Option 1 is the simplest of the two options as you can just send the URLs you want to scrape to your FlareSolverr server and leave it deal with Cloudflare. However, as browsers are memory & bandwidth intensive using this approach can be unreliable and expensive when done at scale.

Option 2 is a small bit trickier, but a more reliable and cost effective approach if you intend to scrape at scale.

We will run through how to use both options below.

Option 1: Send All Requests To FlareSolverr​

The first option is to send all the URLs you want to scrape to FlareSolverr and have it manage bypassing Cloudflare and handling the session cookies for you.

This will work but it make your scraper slower, more expensive and unreliable to run as every request will be going through the Selenium browser.

Option 2: Use FlareSolverr To Only Retrieve Valid Cloudflare Cookies​

The other option is to use FlareSolverr to retrieve valid Cloudflare cookies after passing the Cloudflare challenge and then using these cookies with another HTTP client to scrape the subsequent pages you want to scrape.

This is the recommended way of using FlareSolverr but is a small bit trickier.

Here we make the request with FlareSolverr to retrieve valid Cloudflare cookies after passing the Cloudflare challenge then we:

  1. Extract & clean the valid Cloudflare cookies
  2. Extract the user-agent FlareSolverr used to get the cookies
  3. Make a new requests with Python Requests using the FlareSolverr cookies & user-agent to avoid triggering the Cloudflare challenge

User-Agents & IP Addresses

The Cloudflare cookies are linked to the user-agent and IP address that FlareSolverr used when solving the Cloudflare challenge so you need to make sure to use the same user-agent and IP address when making subsequent requests with a different HTTP client.

Controlling FlareSolverr Sessions​

FlareSolverr V2 allowed you to control the creation and destruction of browser sessions, meaning that you can have multiple browser sessions running on the FlareSolverr server.

This meant you could have different browser sessions running for different websites, proxy settings, etc. and you can then choose which ever one you want to use.

An example for this, would be that you are scraping a Cloudflare protected website with a pool of proxy IP addresses. In this case, you will need a unique set of Cloudflare cookies for each IP address you use as otherwise Cloudflare could block the requests as your IP address is changing for a single cookie.

Making POST Requests With FlareSolverr​

FlareSolverr also allows you to make POST requests to Cloudflare protected websites if you need to retrieve valid Cloudflare cookies from POST endpoints.

To do so, you simply need to use request.post instead of request.get in the cmd section of the FlareSolverr post body, and add any POST data you need to send in the postData value of the POST data:

The postData must be a string with application/x-www-form-urlencoded . Eg: a=b&c=d .

Alternatives To FlareSolverr​

FlareSolverr is a powerful tool, however, open source solutions like FlareSolverr often go out of date and stop working due to Cloudflare updates.

Cloudflare and other anti-bots providers monitor the web for open source anti-bot bypassing tools and often develop fixes for them in a couple months that detect/block them.

So if you are thinking of using FlareSolverr to relibaly bypass Cloudflare on a website then an alternative is to use smart proxies that develop and maintain their own private anti-bot bypasses.

These are typically more reliable as it is harder for anti-bot companies like Cloudflare to develop detections for, as they are developed by proxy companies who are financially motivated to stay 1 step ahead of anti-bot companies and fix their bypasses the very minute they stop working.

One of the best options is the ScrapeOps Proxy Aggregator as it integrates over 20 smart proxy providers into the same proxy API, and finds the best/cheapest proxy provider for your target domains.

You can activate ScrapeOps' Anti-Bot Bypasses by simply using the bypass flag to your API request.

For example, the the below code we will use the Cloudflare bypass by adding bypass=cloudflare to the request:

The advantage of taking this approach is that you can use your normal HTTP client and don't have to worry about:

  • Fortifying headless browsers
  • Managing numerous headless browser instances & dealing with memory issues
  • Reverse engineering the anti-bot protection systems

As this is all managed within the ScrapeOps Proxy Aggregator.

You can get a ScrapeOps API key with 1,000 free API credits by signing up here.

More Scrapy Tutorials​

In this guide we've introduced you to the fundamental functionality of Scrapy Splash and how to use it in your own projects.

However, if you would like to learn more about Scrapy Splash then check out the offical documentation here.

If you would like to learn more about different Javascript rendering options for Scrapy, then be sure to check out our other guides:

If you would like to learn more about Scrapy in general, then be sure to check out The Scrapy Playbook.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *