Quay lại danh sách
Xoay IP theo vùng lãnh thổ để tránh chặn khi scraping

Xoay IP theo vùng lãnh thổ để tránh chặn khi scraping

8 tháng 9, 2026

Tại sao cần xoay IP theo vùng lãnh thổ

Khi thu thập dữ liệu từ nhiều quốc gia, việc dùng một IP duy nhất rất dễ bị phát hiện và chặn. Các nền tảng thường kiểm tra hành vi theo địa lý, tần suất truy cập và dấu vân tay trình duyệt. Nếu bạn liên tục gửi yêu cầu từ một quốc gia nhưng nội dung bạn cần thu thập lại phân phối khắp thế giới, hệ thống sẽ nghi ngờ đây là bot.

Cách chọn proxy theo địa lý

RoProxy cung cấp pool proxy rộng khắp 200+ quốc gia. Bạn chỉ cần lọc theo country_code để lấy danh sách proxy phù hợp. Ví dụ:

# Lấy proxy tại Việt Nam
https://proxylist.roproxy.com/?country=VN

Cấu hình xoay IP trong Python

Bước 1: Cài đặt thư viện

pip install requests

Bước 2: Tải danh sách proxy

import requests
import random

def get_proxies(country_code):
    url = f"https://proxylist.roproxy.com/?country={country_code}"
    response = requests.get(url)
    lines = response.text.strip().split('\n')
    proxies = []
    for line in lines:
        parts = line.split(':')
        if len(parts) == 4:
            host, port, user, pwd = parts
            proxy_url = f"http://{user}:{pwd}@{host}:{port}"
            proxies.append(proxy_url)
    return proxies

Bước 3: Sử dụng xoay IP

def fetch_with_rotation(url, countries):
    for country in countries:
        try:
            proxy_list = get_proxies(country)
            if not proxy_list:
                continue
            proxy = random.choice(proxy_list)
            proxies = {
                'http': proxy,
                'https': proxy
            }
            resp = requests.get(url, proxies=proxies, timeout=10)
            if resp.status_code == 200:
                return resp.text
        except Exception as e:
            print(f"Lỗi ở {country}: {e}")
    return None

# Ví dụ sử dụng
countries = ['VN', 'US', 'GB', 'DE', 'FR']
content = fetch_with_rotation('https://example.com/data', countries)

Tối ưu thời gian chờ và retry

Thêm cơ chế retry và delay để giảm thiểu lỗi kết nối:

import time
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

session = requests.Session()
retry_strategy = Retry(
    total=3,
    backoff_factor=1,
    status_forcelist=[429, 500, 502, 503, 504]
)
session.mount('http://', HTTPAdapter(max_retries=retry_strategy))
session.mount('https://', HTTPAdapter(max_retries=retry_strategy))

Kiểm tra hiệu quả xoay IP

Đảm bảo mỗi yêu cầu dùng IP khác nhau:

import json

def check_ip():
    try:
        resp = session.get('https://api.ipify.org?format=json', proxies=proxies, timeout=10)
        return resp.json().get('ip')
    except:
        return None

# In IP hiện tại trước và sau khi đổi proxy
print('IP trước:', check_ip())
print('IP sau:', check_ip())

Xử lý CAPTCHA và rate limit

Nếu gặp CAPTCHA, hãy chuyển sang proxy khác hoặc dùng dịch vụ giải CAPTCHA. Đối với rate limit, thêm thời gian chờ ngẫu nhiên:

import random
import time

time.sleep(random.uniform(1, 3))

Kết luận

Xoay IP theo vùng lãnh thổ không chỉ giúp tránh chặn mà còn tăng độ tin cậy dữ liệu thu thập được. Kết hợp với cơ chế retry thông minh và kiểm tra IP định kỳ, bạn có thể xây dựng scraper bền vững cho mọi thị trường toàn cầu.