From 070cd80342f1656d695b0e4a5df8991a60cdbe9a Mon Sep 17 00:00:00 2001 From: starmen1265 Date: Sun, 8 Mar 2026 23:25:14 +0800 Subject: [PATCH] =?UTF-8?q?fix(zhihu):=20=E4=BF=AE=E5=A4=8D=20Cookie=20?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E6=97=B6=E6=9C=BA=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将 context 创建移到 cookie 设置之前 - 使用 add_cookies 方法替代初始化时传入 - 添加 .gitignore 忽略 __pycache__ 等文件 --- .gitignore | 21 +++++++++++++++++++++ kb-zhihu-metadata/zhihu_extractor.py | 11 ++++++----- 2 files changed, 27 insertions(+), 5 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..63ca30a --- /dev/null +++ b/.gitignore @@ -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 diff --git a/kb-zhihu-metadata/zhihu_extractor.py b/kb-zhihu-metadata/zhihu_extractor.py index 67af68f..0d6f0fc 100644 --- a/kb-zhihu-metadata/zhihu_extractor.py +++ b/kb-zhihu-metadata/zhihu_extractor.py @@ -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): """关闭浏览器"""