1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
| import asyncio import json import urllib.request import base64 import re import time from collections import OrderedDict
class CDPContentFilter: """基于 CDP 的内容过滤器 支持 URL 匹配、域名匹配、正则匹配、资源类型过滤、EasyList 集成 """ def __init__(self, ws): self.ws = ws self._rules = [] self._resource_filters = {} self._url_cache = OrderedDict() self._cache_max = 10000 self._stats = { 'total': 0, 'blocked': 0, 'allowed': 0, 'cached_hits': 0, } self._easylist_matcher = None self._running = False def add_rule(self, pattern, action='block', rule_type='url', options=None): """添加过滤规则 pattern: 匹配模式 action: block / redirect / replace rule_type: url / domain / regex / resource_type """ rule = { 'pattern': pattern, 'action': action, 'type': rule_type, 'options': options or {}, 'id': len(self._rules) + 1, } self._rules.append(rule) return rule['id'] def remove_rule(self, rule_id): """按 ID 移除规则""" self._rules = [r for r in self._rules if r['id'] != rule_id] def clear_rules(self): """清除所有自定义规则""" self._rules.clear() def get_rules(self): """获取所有规则""" return list(self._rules) def set_resource_filter(self, resource_type, action='block'): """设置资源类型过滤 resource_type: Document / Script / Image / Stylesheet / Font / XHR / Fetch / Media / WebSocket / Manifest action: 'block' (阻断) 或 'allow' (放行,默认放行) """ self._resource_filters[resource_type] = action def remove_resource_filter(self, resource_type): """移除资源类型过滤""" self._resource_filters.pop(resource_type, None) def load_easylist(self, rules): """加载 EasyList 规则""" self._easylist_matcher = EasyListMatcher(rules) def _match_rules(self, url, resource_type='', domain=''): """在自定义规则中匹配""" for rule in self._rules: pattern = rule['pattern'] if rule['type'] == 'url': if pattern in url: return rule elif rule['type'] == 'domain': if pattern == domain or domain.endswith('.' + pattern): return rule elif rule['type'] == 'regex': try: if re.search(pattern, url): return rule except re.error: continue elif rule['type'] == 'resource_type': if resource_type == pattern: return rule return None async def _decide(self, url, resource_type='', domain=''): """决定如何处理请求 —— 返回决策结果""" self._stats['total'] += 1 cache_key = f'{url}|{resource_type}' if cache_key in self._url_cache: self._stats['cached_hits'] += 1 return self._url_cache[cache_key] if resource_type in self._resource_filters: action = self._resource_filters[resource_type] result = {'action': action, 'reason': f'resource_type:{resource_type}', 'rule_id': None} self._cache_result(cache_key, result) return result matched = self._match_rules(url, resource_type, domain) if matched: result = {'action': matched['action'], 'reason': f'rule:{matched["type"]}:{matched["pattern"][:40]}', 'rule_id': matched['id']} self._cache_result(cache_key, result) return result if self._easylist_matcher: decision, pattern = self._easylist_matcher.matches(url, resource_type, domain) if decision == 'block': result = {'action': 'block', 'reason': f'easylist:{pattern[:40]}', 'rule_id': None} self._cache_result(cache_key, result) return result elif decision == 'whitelist': result = {'action': 'allow', 'reason': f'easylist_whitelist:{pattern[:40]}', 'rule_id': None} self._cache_result(cache_key, result) return result result = {'action': 'allow', 'reason': 'default', 'rule_id': None} self._cache_result(cache_key, result) return result def _cache_result(self, key, result): """LRU 缓存结果""" if key in self._url_cache: self._url_cache.move_to_end(key) else: self._url_cache[key] = result if len(self._url_cache) > self._cache_max: self._url_cache.popitem(last=False) async def handle_request_paused(self, params): """处理 Fetch.requestPaused 事件""" request_id = params['requestId'] request = params['request'] url = request['url'] resource_type = params.get('resourceType', '') if url.startswith('data:') or url.startswith('blob:'): await self._continue(request_id) return from urllib.parse import urlparse domain = urlparse(url).netloc decision = await self._decide(url, resource_type, domain) if decision['action'] == 'block': self._stats['blocked'] += 1 await self._block(request_id, url, decision['reason']) else: self._stats['allowed'] += 1 await self._continue(request_id) async def _block(self, request_id, url, reason): """阻断请求""" await cdp(self.ws, 'Fetch.failRequest', { 'requestId': request_id, 'errorReason': 'BlockedByClient' }) async def _continue(self, request_id, headers=None): """放行请求""" params = {'requestId': request_id} if headers: params['headers'] = [{'name': k, 'value': v} for k, v in headers.items()] await cdp(self.ws, 'Fetch.continueRequest', params) async def start(self): """启动过滤器""" await cdp(self.ws, 'Page.enable') await cdp(self.ws, 'Fetch.enable', { 'patterns': [{'urlPattern': '*', 'requestStage': 'Request'}] }) self._running = True print('🛡 Content filter started') async def stop(self): """停止过滤器""" await cdp(self.ws, 'Fetch.disable') self._running = False print('🛡 Content filter stopped') def get_stats(self): """获取统计信息""" s = self._stats cache_hit_rate = (s['cached_hits'] / s['total'] * 100) if s['total'] > 0 else 0 block_rate = (s['blocked'] / s['total'] * 100) if s['total'] > 0 else 0 return { **s, 'cache_size': len(self._url_cache), 'cache_hit_rate': f'{cache_hit_rate:.1f}%', 'block_rate': f'{block_rate:.1f}%', } def print_stats(self): """打印统计信息""" s = self.get_stats() print('=' * 50) print(f'📊 Content Filter Statistics') print('=' * 50) print(f'Total requests: {s["total"]}') print(f'Blocked: {s["blocked"]} ({s["block_rate"]})') print(f'Allowed: {s["allowed"]}') print(f'Cache hits: {s["cached_hits"]} ({s["cache_hit_rate"]})') print(f'Cache size: {s["cache_size"]} entries') print('=' * 50)
async def run_content_filter(): ws_url = get_ws() async with websockets.connect(ws_url, max_size=2**24) as ws: filter_ = CDPContentFilter(ws) filter_.add_rule('doubleclick.net', action='block', rule_type='domain') filter_.add_rule('google-analytics.com', action='block', rule_type='domain') filter_.add_rule('/ads/', action='block', rule_type='url') filter_.set_resource_filter('Image', action='block') filter_.set_resource_filter('Font', action='block') await filter_.start() async def event_loop(): async for msg in ws: try: data = json.loads(msg) except json.JSONDecodeError: continue if data.get('method') == 'Fetch.requestPaused': await filter_.handle_request_paused(data['params']) elif data.get('method') == 'Page.frameStoppedLoading': filter_.print_stats() await cdp(ws, 'Page.navigate', {'url': 'https://example.com'}) await event_loop()
|