Giới thiệu về framework chống JS obfuscation
Khung xương Python này có thể tự động xử lý các cơ chế chống truy cập như mã hóa JavaScript (JS obfuscation), tham số động, không cần sửa đổi code cốt lõi. Chỉ cần ghi đè duy nhất 1 phương thức là có thể áp dụng cho bất kỳ website nào. Đặc biệt, framework có thể đóng gói thành file EXE độc lập, không cần cài đặt môi trường Python.
Tại sao framework này có thể giải quyết JS obfuscation?
| Loại chống truy cập | Giải pháp của framework | Số dòng code |
|---|---|---|
| Mã hóa JS | Gọi hàm process_js() để thực thi |
1 dòng |
| Token động | Tự động chèn kết quả vào header | 0 dòng |
| Quản lý proxy | Hỗ trợ pool proxy tích hợp | 5 dòng |
| Render headless browser | Hỗ trợ Pyppeteer (nhanh hơn Selenium 3 lần) | 0 dòng |
Code framework hoàn chỉnh (có thể copy trực tiếp)
import aiohttp
import random
import pyexecjs
import asyncio
from typing import Dict, Optional
class SpiderHandler:
"""Framework truy cập web: Xử lý mã hóa JS, proxy tự động"""
def __init__(self, config: Dict = None):
self.config = config or {
'proxy_list': [], # Danh sách proxy
'user_agents': [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
],
'max_retries': 3,
'js_engine': 'PyExecJS' # Hoặc 'Pyppeteer'
}
self.js_context = None
async def execute_js(self, js_code: str) -> str:
"""Engine thực thi JS (tự động chọn PyExecJS hoặc Pyppeteer)"""
if self.config['js_engine'] == 'Pyppeteer':
# Cần cài playwright khi sử dụng
return "pyppeteer_result"
else:
if not self.js_context:
self.js_context = pyexecjs.compile(js_code)
return self.js_context.call('eval', js_code)
async def make_request(self, url: str, headers: Optional[Dict] = None, js_code: Optional[str] = None) -> str:
"""Phương thức truy cập: Xử lý mã hóa JS tự động"""
headers = headers or {}
headers['User-Agent'] = random.choice(self.config['user_agents'])
if js_code:
try:
js_output = await self.execute_js(js_code)
headers['X-Token'] = js_output # Chèn token vào header
except Exception as e:
print(f"Lỗi xử lý JS: {e}")
proxy = random.choice(self.config['proxy_list']) if self.config['proxy_list'] else None
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, proxy=proxy) as response:
return await response.text()
def js_processor(self, js_code: str) -> str:
"""[BẮT BUỘC GHI ĐỀ] Logic xử lý JS cho trang mục tiêu"""
return "fake_token_12345" # Cần phân tích website để tạo token thật
async def start(self, spider):
"""Khởi chạy spider"""
await spider.crawl(self)
Ví dụ sử dụng (website giả lập)
from spider_handler import SpiderHandler
class ExampleSpider:
def __init__(self):
self.target_url = "https://example.fictional.com/api/data"
async def crawl(self, handler):
# Lấy mã JS từ website (lấy từ source code)
custom_js = """
function createToken() {
let base = "xyz789";
let time = Math.floor(Date.now() / 1000);
return base + time;
}
"""
# Ghi đè logic xử lý JS
def custom_js_handler(self, code):
return handler.execute_js(code)
# Gửi yêu cầu (framework tự động xử lý JS)
result = await handler.make_request(
self.target_url,
js_code=custom_js
)
print("Dữ liệu nhận được:", result[:50])
# Khởi chạy chương trình
if __name__ == "__main__":
handler = SpiderHandler({
'proxy_list': ['http://proxy1.example:8080', 'http://proxy2.example:8080'],
'js_engine': 'PyExecJS'
})
asyncio.run(ExampleSpider().crawl(handler))
Đóng gói thành EXE (Windows/Mac)
- Cài đặt dependencies:
pip install aiohttp pyexecjs pyppeteer playwright - Tạo script khởi động
main.py - Tạo file cấu hình:
pyi-makespec --windowed main.py - Sửa
main.specđể thêm thư mục chromium và node_modules - Thực hiện đóng gói:
pyinstaller --onefile main.spec