Как соскабливать файлы cookie cf_clearance с сайтов, защищенных Cloudflare
In this article, I’ll walk you through the process of scraping the cf_clearance cookie from Cloudflare-protected sites and show you how to use it to overcome Cloudflare’s restrictions, making it easier for you to scrape the data you need.
What is the cf_clearance Cookie?
Cloudflare Cloudflare — популярный сервис защиты сайтов, который обнаруживает и блокирует автоматизированный трафик. Он использует разные методы для выявления ботов, включая анализ IP-адресов, обнаружение подозрительных шаблонов поведения и проверку запросов с помощью CAPTCHA или JavaScript-челленджей.
When you visit a Cloudflare-protected website, you often face these challenges, which you must solve before being granted access to the site. Once you successfully pass these challenges, Cloudflare issues a special cookie called cf_clearance. This cookie serves as proof that you have solved the security challenge and allows you to bypass Cloudflare’s protection and access the website.
However, there’s a catch: to scrape the content behind Cloudflare successfully, you need to retrieve this cf_clearance cookie and use it in subsequent requests. If the cookie is missing or expired, Cloudflare will block your scraping attempts.
Why is Scraping the cf_clearance Cookie Important?
When scraping a Cloudflare-protected site, the cf_clearance cookie is essential. If you don’t pass the challenge and retrieve the cookie, your requests will be blocked by Cloudflare. It acts as an access key that allows you to bypass Cloudflare’s security and scrape the data you need.
Once you obtain the cf_clearance cookie, you can use it to authenticate your requests. However, it’s important to note that the cookie is session-based, which means you must maintain the same IP address and User-Agent during the entire scraping session. If you change either, Cloudflare will block your access.
How to Scrape the cf_clearance Cookie?
Scraping the cf_clearance cookie from a Cloudflare-protected website can be tricky since Cloudflare uses several techniques to detect and block bots. In this section, I’ll walk you through how to scrape the cf_clearance cookie using a tool called CF-Clearance-Scraper. This command-line tool automates the process of solving the Cloudflare challenges and retrieving the cf_clearance cookie.
Шаг 1: Установите CF-Clearance-Scraper
Первый шаг — установить пакет CF-Clearance-Scraper. Этот инструмент предназначен для работы с Python 3.10 и запускает в фоновом режиме экземпляр headless Chrome, чтобы проходить проверки Cloudflare.
Клонируйте репозиторий: Начните с клонирования репозитория CF-Clearance-Scraper из GitHub:
git clone https://github.com/Xewdy444/CF-Clearance-Scraper
Установите необходимые зависимости: После клонирования репозитория перейдите в папку и установите необходимые зависимости с помощью pip:
cd CF-Clearance-Scraper
pip3 install -r requirements.txt
Now, you’re ready to start scraping the cf_clearance cookie from a Cloudflare-protected website.
Шаг 2: Параметры CF-Clearance-Scraper
CF-Clearance-Scraper works by running the main.py file with a set of parameters. These parameters control how the tool interacts with Cloudflare’s protection and retrieve the cf_clearance cookie.
Основные параметры:
- -f: Указывает имя выходного файла, в котором cookies будут сохранены в формате JSON.
- -t: Устанавливает таймаут запроса в секундах. Это определяет, как долго инструмент будет ждать прохождения челленджа.
- -p: Указывает URL прокси, который необходим, чтобы избежать обнаружения при скрейпинге.
- -ua: Устанавливает заголовок User-Agent для запроса. Важно использовать корректный User-Agent, чтобы избежать обнаружения.
- URL: URL сайта под защитой Cloudflare, который вы хотите скрейпить.
Команда для запуска CF-Clearance-Scraper выглядит так:
python main.py -p <PROXY_ADDRESS> -t <TIMEOUT_IN_SECONDS> -ua "<USER_AGENT_STRING>" -f <COOKIE_FILE.json> <TARGET_URL>
Step 3: Scraping the cf_clearance Cookie
To scrape the cf_clearance cookie, you need to run the CF-Clearance-Scraper tool with the appropriate parameters. For example, let’s say you want to scrape the cf_clearance cookie from a Cloudflare-protected page. You would run the following command:
python main.py -p http://190.58.248.86:80 -t 60 -ua "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36" -f cookies.json https://www.scrapingcourse.com/cloudflare-challenge
В этой команде:
- Proxy: Мы используем прокси, чтобы избежать обнаружения. Вы можете использовать любой прокси на свой выбор, например бесплатные прокси или премиум-прокси для веб-скрапинга.
- Timeout: Мы устанавливаем таймаут в 60 секунд, то есть инструмент будет ждать до 60 секунд, чтобы пройти челлендж Cloudflare.
- User-Agent: Мы используем стандартную строку User-Agent, имитирующую реальный браузер.
- Выходной файл: The cookies will be saved to a file named cookies.json.
Once the command is executed successfully, the tool will print the cf_clearance cookie in the terminal, and all the cookies will be saved in the cookies.json file.
Step 4: Extracting the cf_clearance Cookie Programmatically
While the cf_clearance cookie will be outputted in the terminal, it’s often more convenient to extract it programmatically. You can use Python’s subprocess module to run the CF-Clearance-Scraper tool from within your Python script and extract the cf_clearance cookie using regular expressions.
Here’s an example Python script that runs the CF-Clearance-Scraper tool and extracts the cf_clearance cookie:
импорт subprocess
импорт re
def cf_clearance_scraper(url, proxy, user_agent):
command = [
"python",
"main.py",
"-p", proxy,
"-t",
"60",
"-ua",
user_agent,
"-f",
"cookies.json",
url,
]
попробуйте:
# Run the command and capture the output
process = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=Правда,
)
output = process.stdout
# Extract the cf_clearance value from the logs using regex
match = re.search(r"cf_clearance=([^s] )", output)
если match:
cf_clearance = match.group(1)
возврат cf_clearance
else:
возврат Нет
кроме Исключение в роли e:
печать(f"Error running the command: {e}")
возврат Нет
# Example usage
url = "https://www.scrapingcourse.com/cloudflare-challenge"
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36"
прокси = "http://190.58.248.86:80"
cf_clearance = cf_clearance_scraper(url, proxy, user_agent)
если cf_clearance:
печать(f"cf_clearance cookie: {cf_clearance}")
else:
печать("Failed to retrieve cf_clearance cookie.")
This script runs the CF-Clearance-Scraper tool with the specified parameters, captures the output, and extracts the cf_clearance cookie using a regular expression. If successful, it prints the cookie; otherwise, it prints an error message.
Step 5: Using the cf_clearance Cookie to Bypass Cloudflare
Now that you have the cf_clearance cookie, you can use it to bypass Cloudflare and make scraping requests to the protected website. In this step, we will use the requests library to make HTTP requests while passing the cf_clearance cookie.
Here’s how to integrate the cf_clearance cookie into your scraping code:
импорт requests
def скребок(url, cf_clearance, proxy, user_agent):
session = requests.Session()
# Set the cf_clearance cookie in the session
session.cookies.set("cf_clearance", cf_clearance)
# Set the User-Agent header
session.headers.update({"User-Agent": user_agent})
# Set the proxy for the session
session.proxies.update(
{
"http": прокси,
"https": proxy,
}
)
попробуйте:
# Make the request to the target URL
response = session.get(url)
response.raise_for_status()
возврат response.text
кроме requests.exceptions.RequestException в роли e:
возврат f"Error making request: {e}"
# Example usage
response = scraper(url, cf_clearance, proxy, user_agent)
печать(response)
In this code, the scraper function accepts the cf_clearance cookie, along with the target URL, proxy, and User-Agent. It creates a persistent session using the requests.Session() object and sets the cf_clearance cookie, User-Agent, and proxy for the session. The session is then used to make a GET request to the target URL.
Заключение
By scraping the cf_clearance cookie and using it for your requests, you can bypass Cloudflare’s protection and scrape data from protected websites. While CF-Clearance-Scraper is effective, it has some limitations, including the need for a consistent IP and User-Agent, as well as the risk of cookie expiration during the session.
Чтобы снизить риск блокировок IP или истекших cookies, важно использовать ротационные прокси и эффективно управлять сессиями. Такие сервисы, как Яркие данные может предложить продвинутое управление прокси и sticky-сессии, помогая поддерживать стабильный доступ к вашим ресурсам. С этими советами вы сможете эффективнее собирать данные с сайтов, защищенных Cloudflare.

