如何解决Python调用Bard时会话Cookie频繁变更的问题?
一、自动获取并更新会话Cookie
手动更新Cookie效率极低,可通过模拟浏览器登录流程自动抓取并维护Cookie:
- 用Selenium模拟登录提取Cookie
通过Chrome浏览器的用户数据目录,首次登录后后续可自动复用登录状态,无需重复手动操作:
from selenium import webdriver from selenium.webdriver.chrome.options import Options import requests from bardapi import Bard, SESSION_HEADERS def get_bard_cookies(): chrome_options = Options() # 保存浏览器登录状态,避免重复登录 chrome_options.add_argument("user-data-dir=./chrome_bard_profile") driver = webdriver.Chrome(options=chrome_options) driver.get("https://bard.google.com/") # 首次运行需手动完成登录,之后按回车继续 input("登录完成后按回车继续...") cookies = driver.get_cookies() session = requests.Session() # 只提取需要的三个Cookie target_cookies = ["__Secure-1PSID", "__Secure-1PSIDCC", "__Secure-1PSIDTS"] for cookie in cookies: if cookie['name'] in target_cookies: session.cookies.set(cookie['name'], cookie['value']) driver.quit() return session # 初始化自动获取的会话 session = get_bard_cookies() token = "mytokenhere" session.headers = SESSION_HEADERS bard = Bard(token=token, session=session)
- Cookie失效自动重试
在请求逻辑中加入异常捕获,当请求失败时自动重新获取Cookie:
def get_bard_safe_response(bard, prompt): try: return bard.get_answer(prompt) except Exception as e: print("Cookie失效,重新获取会话...") global session, bard session = get_bard_cookies() bard = Bard(token=token, session=session) return bard.get_answer(prompt) # 调用示例 answer = get_bard_safe_response(bard, "Summarize this transcription: " + s)
二、不依赖会话Cookie的官方替代方案
Google官方未提供无Cookie的Bard API,但可使用PaLM API(Bard基于PaLM模型开发),这是合规稳定的官方调用方式:
- 安装依赖
pip install google-generativeai
- PaLM API调用代码示例
需先在Google Cloud控制台创建并获取API密钥,替换代码中的YOUR_API_KEY:
import google.generativeai as genai # 配置API密钥 genai.configure(api_key="YOUR_GOOGLE_CLOUD_API_KEY") # 初始化文本生成模型 model = genai.GenerativeModel('models/text-bison-001') # 读取并处理长文本 file_path = 'prova2.1.txt' with open(file_path, 'r', encoding='ISO-8859-1') as file: transcription = file.read() def split_long_string(input_string, max_length): divided_strings = [] for i in range(0, len(input_string), max_length): divided_strings.append(input_string[i:i + max_length]) return divided_strings divided_strings = split_long_string(transcription, 7000) combined_response = "" # 分段生成摘要 for s in divided_strings: response = model.generate_content(f"Summarize this transcription: {s}") combined_response += response.text + "\n" # 合并所有摘要 final_response = model.generate_content(f"Join these summaries into a coherent whole: {combined_response}") print(final_response.text)
注意事项
- 使用Selenium时,需保证Chrome浏览器与ChromeDriver版本匹配。
- PaLM API提供免费测试额度,超出后需付费使用,注意API密钥保密。
内容的提问来源于stack exchange,提问作者ilpoppattuso
相关产品推荐
相关产品推荐

