fix(zhihu): 修复 Cookie 设置时机问题

- 将 context 创建移到 cookie 设置之前
- 使用 add_cookies 方法替代初始化时传入
- 添加 .gitignore 忽略 __pycache__ 等文件
This commit is contained in:
2026-03-08 23:25:14 +08:00
parent 727cfc183a
commit 070cd80342
2 changed files with 27 additions and 5 deletions
+21
View File
@@ -0,0 +1,21 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
*.egg-info/
.eggs/
dist/
build/
# IDE
.idea/
.vscode/
*.swp
*.swo
# Misc
.DS_Store
*.log
.env
+6 -5
View File
@@ -41,16 +41,17 @@ class PlaywrightBrowser:
'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'
}
self.context = self.browser.new_context(**context_options)
# 如果提供了 Cookie,设置 Cookie
if cookie:
context_options['cookies'] = self._parse_cookie(cookie)
self._add_cookies(cookie)
self.context = self.browser.new_context(**context_options)
self.page = self.context.new_page()
self.page.set_default_timeout(self.timeout)
def _parse_cookie(self, cookie_str: str) -> list:
"""解析 Cookie 字符串为 Playwright 格式"""
def _add_cookies(self, cookie_str: str):
"""添加 Cookie 到浏览器上下文"""
cookies = []
for item in cookie_str.split(';'):
item = item.strip()
@@ -65,7 +66,7 @@ class PlaywrightBrowser:
'httpOnly': False,
'sameSite': 'Lax'
})
return cookies
self.context.add_cookies(cookies)
def close(self):
"""关闭浏览器"""