如何用Python Selenium获取Datto OAuth2.0访问令牌?
解决Datto OAuth2.0认证流程获取Access Token的问题
核心问题分析
你遇到的认证弹窗是浏览器内置的HTTP Basic认证框,不是普通网页弹窗或JS Alert:
- 这种弹窗由浏览器直接触发,开发者工具无法捕获其HTML结构
- Selenium的
Alert类可处理它,但不能用page_source获取内容,需用专门的认证方法
方案一:用Selenium处理HTTP Basic认证
修改你的代码,替换手动模拟按键的部分,用Selenium内置方法自动填写凭证:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time # OAuth2.0 凭证 client_id = 'public-client' client_secret = 'public' auth_user = 'YOUR_PUBLIC_KEY_HERE' auth_pass = 'YOUR_SECRET_KEY_HERE' access_token_url = "https://zinfandel-api.centrastage.net/auth/oauth/token" browser = webdriver.Chrome(service=Service(ChromeDriverManager().install())) browser.get(access_token_url) # 等待HTTP Basic认证框出现,自动完成认证 try: WebDriverWait(browser, 10).until(EC.alert_is_present()) alert = browser.switch_to.alert alert.authenticate(client_id, client_secret) time.sleep(2) except Exception as e: print("认证框处理失败:", str(e)) # 处理API密钥登录(若后续有网页表单) try: # 等待用户名输入框加载完成 user_name_field = WebDriverWait(browser, 10).until( EC.presence_of_element_located(("name", "username")) ) password_field = browser.find_element("name", "password") user_name_field.send_keys(auth_user) password_field.send_keys(auth_pass) password_field.submit() # 等待跳转后提取access token(示例逻辑,需根据实际页面调整) time.sleep(3) page_source = browser.page_source if "access_token" in page_source: access_token = page_source.split('"access_token":"')[1].split('"')[0] print("获取到Access Token:", access_token) except Exception as e: print("登录过程失败:", str(e)) browser.quit()
方案二:跳过Selenium,用requests直接请求(更高效)
自动化获取token优先用requests库直接调用OAuth接口,无需依赖浏览器:
import requests client_id = "public-client" client_secret = "public" auth_user = "YOUR_PUBLIC_KEY_HERE" auth_pass = "YOUR_SECRET_KEY_HERE" token_url = "https://zinfandel-api.centrastage.net/auth/oauth/token" # 构建OAuth2密码模式请求参数 request_data = { "grant_type": "password", "username": auth_user, "password": auth_pass, "scope": "" # 按Datto文档填写权限范围,无特殊需求留空 } # 发送POST请求,client_id和client_secret作为HTTP Basic认证凭证 response = requests.post(token_url, data=request_data, auth=(client_id, client_secret)) if response.status_code == 200: token_info = response.json() access_token = token_info["access_token"] refresh_token = token_info.get("refresh_token") print(f"Access Token: {access_token}") print(f"Refresh Token: {refresh_token}") else: print(f"请求失败,状态码:{response.status_code}") print("错误信息:", response.text)
额外提示
- 用Selenium时,还可以直接在URL中嵌入认证信息绕过弹窗,格式为:
直接调用https://{client_id}:{client_secret}@zinfandel-api.centrastage.net/auth/oauth/tokenbrowser.get()即可,不会弹出认证框。 - 长期自动化场景优先选方案二,Selenium仅在必须可视化流程时使用。
内容的提问来源于stack exchange,提问作者bjforesthowell
相关产品推荐
相关产品推荐

