|
|
@@ -199,6 +199,7 @@ class BasePublisher(ABC):
|
|
|
self.browser: Optional[Browser] = None
|
|
|
self.context: Optional[BrowserContext] = None
|
|
|
self.page: Optional[Page] = None
|
|
|
+ self.playwright = None # Playwright server instance, must be stopped in close_browser()
|
|
|
self.on_progress: Optional[Callable[[int, str], None]] = None
|
|
|
self.user_id: Optional[int] = None
|
|
|
self.publish_task_id: Optional[int] = None
|
|
|
@@ -319,7 +320,7 @@ class BasePublisher(ABC):
|
|
|
print(
|
|
|
f"[{self.platform_name}] init_browser: headless={self.headless}", flush=True
|
|
|
)
|
|
|
- playwright = await async_playwright().start()
|
|
|
+ self.playwright = await async_playwright().start()
|
|
|
|
|
|
proxy = proxy_config or self.proxy_config
|
|
|
has_proxy = proxy and isinstance(proxy, dict) and proxy.get("server")
|
|
|
@@ -347,7 +348,7 @@ class BasePublisher(ABC):
|
|
|
chrome_launched = False
|
|
|
for channel in ("chrome", "msedge"):
|
|
|
try:
|
|
|
- self.browser = await playwright.chromium.launch(
|
|
|
+ self.browser = await self.playwright.chromium.launch(
|
|
|
channel=channel, **launch_args
|
|
|
)
|
|
|
print(
|
|
|
@@ -367,7 +368,7 @@ class BasePublisher(ABC):
|
|
|
f"[{self.platform_name}] 回退到 Playwright Chromium(注意: 更容易被平台检测)",
|
|
|
flush=True,
|
|
|
)
|
|
|
- self.browser = await playwright.chromium.launch(**launch_args)
|
|
|
+ self.browser = await self.playwright.chromium.launch(**launch_args)
|
|
|
|
|
|
# 生成浏览器上下文参数(带反检测配置)
|
|
|
if STEALTH_AVAILABLE:
|
|
|
@@ -441,10 +442,30 @@ class BasePublisher(ABC):
|
|
|
|
|
|
async def close_browser(self):
|
|
|
"""关闭浏览器"""
|
|
|
+ if self.page:
|
|
|
+ try:
|
|
|
+ await self.page.close()
|
|
|
+ except Exception:
|
|
|
+ pass
|
|
|
+ self.page = None
|
|
|
if self.context:
|
|
|
- await self.context.close()
|
|
|
+ try:
|
|
|
+ await self.context.close()
|
|
|
+ except Exception:
|
|
|
+ pass
|
|
|
+ self.context = None
|
|
|
if self.browser:
|
|
|
- await self.browser.close()
|
|
|
+ try:
|
|
|
+ await self.browser.close()
|
|
|
+ except Exception:
|
|
|
+ pass
|
|
|
+ self.browser = None
|
|
|
+ if getattr(self, 'playwright', None):
|
|
|
+ try:
|
|
|
+ await self.playwright.stop()
|
|
|
+ except Exception:
|
|
|
+ pass
|
|
|
+ self.playwright = None
|
|
|
|
|
|
async def human_like_delay(self, min_ms: int = 100, max_ms: int = 500):
|
|
|
"""模拟人类操作延迟"""
|