TheSmallHanCat commited on
Commit
f63c37f
·
1 Parent(s): a374db7

fix: 无头模式下代理不生效

Browse files
Files changed (1) hide show
  1. src/services/browser_captcha.py +34 -3
src/services/browser_captcha.py CHANGED
@@ -4,12 +4,37 @@
4
  """
5
  import asyncio
6
  import time
7
- from typing import Optional
 
8
  from playwright.async_api import async_playwright, Browser, BrowserContext
9
 
10
  from ..core.logger import debug_logger
11
 
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  class BrowserCaptchaService:
14
  """浏览器自动化获取 reCAPTCHA token(单例模式)"""
15
 
@@ -60,9 +85,15 @@ class BrowserCaptchaService:
60
  ]
61
  }
62
 
63
- # 如果有代理,添加代理配置
64
  if proxy_url:
65
- launch_options['proxy'] = {'server': proxy_url}
 
 
 
 
 
 
66
 
67
  self.browser = await self.playwright.chromium.launch(**launch_options)
68
  self._initialized = True
 
4
  """
5
  import asyncio
6
  import time
7
+ import re
8
+ from typing import Optional, Dict
9
  from playwright.async_api import async_playwright, Browser, BrowserContext
10
 
11
  from ..core.logger import debug_logger
12
 
13
 
14
+ def parse_proxy_url(proxy_url: str) -> Optional[Dict[str, str]]:
15
+ """解析代理URL,分离协议、主机、端口、认证信息
16
+
17
+ Args:
18
+ proxy_url: 代理URL,格式:protocol://[username:password@]host:port
19
+
20
+ Returns:
21
+ 代理配置字典,包含server、username、password(如果有认证)
22
+ """
23
+ proxy_pattern = r'^(socks5|http|https)://(?:([^:]+):([^@]+)@)?([^:]+):(\d+)$'
24
+ match = re.match(proxy_pattern, proxy_url)
25
+
26
+ if match:
27
+ protocol, username, password, host, port = match.groups()
28
+ proxy_config = {'server': f'{protocol}://{host}:{port}'}
29
+
30
+ if username and password:
31
+ proxy_config['username'] = username
32
+ proxy_config['password'] = password
33
+
34
+ return proxy_config
35
+ return None
36
+
37
+
38
  class BrowserCaptchaService:
39
  """浏览器自动化获取 reCAPTCHA token(单例模式)"""
40
 
 
85
  ]
86
  }
87
 
88
+ # 如果有代理,解析并添加代理配置
89
  if proxy_url:
90
+ proxy_config = parse_proxy_url(proxy_url)
91
+ if proxy_config:
92
+ launch_options['proxy'] = proxy_config
93
+ auth_info = "auth=yes" if 'username' in proxy_config else "auth=no"
94
+ debug_logger.log_info(f"[BrowserCaptcha] 代理配置: {proxy_config['server']} ({auth_info})")
95
+ else:
96
+ debug_logger.log_warning(f"[BrowserCaptcha] 代理URL格式错误: {proxy_url}")
97
 
98
  self.browser = await self.playwright.chromium.launch(**launch_options)
99
  self._initialized = True