在Python中读取token值通常有以下几种方法:
从响应头中获取token:
使用`requests`库发送HTTP请求,并从响应头中提取token值。
import requests
url = 'http://xxx.nhf.cn/api/businessAccountInfo/v1.4/userLogin'
data = {'phoneNum': '', 'password': ''}
response = requests.post(url, json=data)
token = response.headers['token']
从响应体中获取token:
如果token存在于响应体的字典数据中,可以直接从响应体中提取。
import requests
url = 'http://xxx.nhf.cn/api/fresh/v1.4/ordersList'
data = {'pageNo': 1, 'pageSize': 10}
headers = {'token': token}
response = requests.post(url, json=data, headers=headers)
print(response.json())
使用第三方库获取token:
例如,使用`requests_oauthlib`或`requests_http_auth`库处理认证流程。
从环境变量中获取token:
使用`os`模块读取环境变量中的token值。
import os
token = os.environ.get('TOKEN')
通过Selenium获取token:
使用Selenium登录并获取token值,通常token会存储在localStorage或sessionStorage中。
from seleniumwire import webdriver
driver = webdriver.Chrome()
agent = driver.requests
for request in agent:
if request.url == 'www.aaaa.com':
print(request.url, request.headers)
从配置文件中读取token:
将token值保存到YAML或其他配置文件中,然后读取。
import yaml
def write_token(res):
curPath = os.path.abspath(os.path.dirname(__file__))
yamlPath = os.path.abspath(os.path.dirname(curPath) + os.path.sep + 'configs/access_token.yml')
tokenValue = {'access_token': res['access_token']}
with open(yamlPath, 'w', encoding='utf-8') as f:
yaml.dump(tokenValue, f)
def read_token():
yamlPath = os.path.abspath(os.path.dirname(__file__)) + os.path.sep + 'configs/access_token.yml'
with open(yamlPath, 'r', encoding='utf-8') as f:
token_data = yaml.safe_load(f)
return token_data['access_token']
选择合适的方法读取token取决于你的具体需求和应用场景。请根据你的情况选择最适合的方法