Kiểm thử bản địa hoá và xác minh quảng cáo theo khu vực bằng Playwright + proxy dân cư

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

Localization Testing and Regional Ad Verification with Playwright + Residential Proxies

You have just launched the Vietnamese version of a landing page, are running ad campaigns targeting users in Vietnam, Japan, and the US, and want to ensure each market sees the correct content: the right language, currency, promotional banners, and cookie policies. Opening a browser from an office in Hanoi or Ho Chi Minh City only shows you the “Vietnam” version. Turning on a corporate VPN often results in a datacenter IP, and many CDN, A/B testing, or ad server systems handle datacenter IPs differently than real users. This article guides you on how to build a compact localization QA and ad verification process using Python + Playwright, running through regional residential proxies, taking screenshots, and automatically checking a few basic localization markers. Disclosure: I work at ipvora, a residential proxy service. The examples below use environment variables and do not depend on any specific provider.

1. Tại sao cần IP theo khu vực khi QA?

Một trang web có thể thay đổi nội dung dựa trên nhiều tín hiệu: Địa chỉ IP (GeoIP ở CDN, ở backend, hoặc ở nền tảng quảng cáo), Header Accept-Language mà trình duyệt gửi, múi giờ và locale của trình duyệt (JavaScript đọc qua Intl API), hoặc Cookie/localStorage từ lần truy cập trước. Nếu chỉ đổi Accept-Language mà IP vẫn ở Việt Nam, bạn đang kiểm tra một tổ hợp mà người dùng Nhật thật gần như không bao giờ tạo ra. Ngược lại, nếu chỉ đổi IP mà trình duyệt vẫn báo múi giờ Asia/Ho_Chi_Minh, một số script chống gian lận hoặc logic hiển thị sẽ cho kết quả khác. Muốn mô phỏng sát thực tế, hãy đổi cả ba: IP, ngôn ngữ, múi giờ. Proxy dân cư hữu ích ở đây vì IP thuộc nhà mạng phục vụ hộ gia đình, nên cách CDN và ad server phân loại lưu lượng gần với người dùng thật hơn so với IP datacenter.

2. Choosing between rotating or static for QA?

Rotating proxies with sticky sessions are suitable for short checks: opening a page, taking a screenshot, and checking a few elements. You only need the IP to remain constant for the few minutes of a run. Static proxies are suitable when you need to whitelist an IP in a staging environment, or run the same scenario daily and want to compare results between days without being disturbed by IP changes. For example, with ipvora: rotating proxies are billed by GB, keeping sessions for 1–120 minutes; static proxies are rented by IP per month, 5 Mbps/IP, with unlimited traffic during the rental period; both support HTTP, HTTPS, and SOCKS5, with IPs in Vietnam, the US, Japan, and Europe. With localization QA, each run usually only costs a few MB (one page + resources), so what matters more is the correct region and stability throughout the run.

3. Cấu hình theo khu vực bằng biến môi trường

Đừng hard-code thông tin proxy trong mã nguồn. Hãy dùng một biến cho mỗi khu vực:

export PROXY_URL_VN="http://USER:PASS@HOST:PORT"
export PROXY_URL_JP="http://USER:PASS@HOST:PORT"
export PROXY_URL_US="http://USER:PASS@HOST:PORT"
export TARGET_URL="https://example.com/"

Thay USER, PASS, HOST, PORT bằng chuỗi kết nối proxy của khu vực tương ứng từ nhà cung cấp bạn dùng. Lưu ý Playwright yêu cầu tách server, username, password thành các trường riêng, nên ta sẽ tự phân tích URL. Cài đặt: pip install playwright và python -m playwright install chromium.

4. Multi-region testing script

The script below, for each region: Opens a new browser context with the corresponding proxy, locale, and timezone. Checks the exit IP and country via a public API. Opens the page to be tested, reads the lang attribute of the html tag, and finds the expected currency symbol. Takes a full-page screenshot and writes the results to a JSON file.

import json
import os
import re
from pathlib import Path
from urllib.parse import urlsplit
from playwright.sync_api import sync_playwright

REGIONS = {
    "VN": {"env": "PROXY_URL_VN", "locale": "vi-VN", "timezone": "Asia/Ho_Chi_Minh", "currency": r"₫|VND"},
    "JP": {"env": "PROXY_URL_JP", "locale": "ja-JP", "timezone": "Asia/Tokyo", "currency": r"¥|円|JPY"},
    "US": {"env": "PROXY_URL_US", "locale": "en-US", "timezone": "America/New_York", "currency": r"\$|USD"},
}

TARGET_URL = os.environ.get("TARGET_URL", "https://example.com/")
OUT_DIR = Path("qa_output")

def playwright_proxy(proxy_url):
    """Chuyển http://user:pass@host:port thành dict mà Playwright yêu cầu."""
    parts = urlsplit(proxy_url)
    proxy = {"server": f"{parts.scheme}://{parts.hostname}:{parts.port}"}
    if parts.username:
        proxy["username"] = parts.username
        proxy["password"] = parts.password or ""
    return proxy

def check_region(browser, code, cfg):
    proxy_url = os.environ.get(cfg["env"])
    if not proxy_url:
        return {"region": code, "skipped": f"thiếu biến {cfg['env']}"}
    
    context = browser.new_context(
        proxy=playwright_proxy(proxy_url),
        locale=cfg["locale"],
        timezone_id=cfg["timezone"],
        viewport={"width": 1366, "height": 900},
    )
    page = context.new_page()
    result = {"region": code}
    try:
        page.goto("https://ipinfo.io/json", timeout=30_000)
        info = json.loads(page.inner_text("body"))
        result["exit_ip"] = info.get("ip")
        result["exit_country"] = info.get("country")
        result["geo_ok"] = info.get("country") == code
        
        page.goto(TARGET_URL, wait_until="networkidle", timeout=60_000)
        result["html_lang"] = page.get_attribute("html", "lang")
        result["browser_tz"] = page.evaluate("Intl.DateTimeFormat().resolvedOptions().timeZone")
        text = page.inner_text("body")
        result["currency_found"] = bool(re.search(cfg["currency"], text))
        
        shot = OUT_DIR / f"{code}.png"
        page.screenshot(path=str(shot), full_page=True)
        result["screenshot"] = str(shot)
    except Exception as exc:
        result["error"] = repr(exc)
    finally:
        context.close()
    return result

def main():
    OUT_DIR.mkdir(exist_ok=True)
    with sync_playwright() as p:
        browser = p.chromium.launch()
        results = [check_region(browser, c, cfg) for c, cfg in REGIONS.items()]
        browser.close()
    (OUT_DIR / "report.json").write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8")
    for r in results: print(r)

if __name__ == "__main__":
    main()

Một vài điểm cần lưu ý

Mỗi khu vực một context riêng. Context trong Playwright tách biệt cookie và storage, nên kết quả khu vực này không “rò” sang khu vực khác. Kiểm tra IP trước rồi mới mở trang. Nếu exit_country không khớp, kết quả bản địa…