使用Python调用天眼查API查询企业信息全攻略
2025.09.18 16:00浏览量:0简介:本文详细介绍了如何通过Python调用天眼查API接口实现企业信息的自动化查询,涵盖API认证、请求构造、数据处理及异常处理等关键环节,帮助开发者快速构建高效的企业信息检索系统。
使用Python调用天眼查API查询企业信息全攻略
一、天眼查API核心价值解析
天眼查作为国内领先的企业信息查询平台,其API接口为开发者提供了结构化、标准化的企业数据获取通道。相较于传统网页爬取方式,API调用具有三大优势:
典型应用场景包括:
- 金融机构贷前尽调自动化
- 供应链企业资质核验
- 商业情报分析系统建设
- 法律风险预警系统开发
二、Python环境准备与依赖安装
2.1 基础环境配置
# 推荐Python 3.7+版本
import sys
print(sys.version) # 应显示3.7.x或更高版本
2.2 核心依赖库安装
pip install requests pandas jsonpath-ng
库名称 | 用途说明 | 版本要求 |
---|---|---|
requests | HTTP请求处理 | ≥2.24.0 |
pandas | 数据结构化处理 | ≥1.1.0 |
jsonpath-ng | JSON数据解析 | ≥1.5.2 |
三、API认证机制详解
3.1 认证方式对比
认证方式 | 安全性 | 适用场景 | 配置复杂度 |
---|---|---|---|
API Key | 中 | 简单查询场景 | ★ |
OAuth2.0 | 高 | 长期集成项目 | ★★★ |
签名验证 | 极高 | 金融级应用 | ★★★★ |
3.2 签名验证实现示例
import hashlib
import time
import hmac
def generate_sign(secret_key, params):
"""
生成HMAC-SHA256签名
:param secret_key: 分配的密钥
:param params: 请求参数字典
:return: 十六进制签名
"""
sorted_params = sorted(params.items(), key=lambda x: x[0])
param_str = '&'.join([f"{k}={v}" for k, v in sorted_params])
timestamp = str(int(time.time()))
message = f"{timestamp}&{param_str}"
return hmac.new(secret_key.encode(), message.encode(), hashlib.sha256).hexdigest()
四、核心查询接口实现
4.1 企业基础信息查询
import requests
import json
def get_company_info(api_key, company_name):
"""
获取企业基础信息
:param api_key: 天眼查分配的API Key
:param company_name: 企业名称(支持模糊查询)
:return: 解析后的企业信息字典
"""
url = "https://api.tianyancha.com/services/open/ic/v2/company/search"
headers = {
"X-Auth-Token": api_key,
"Content-Type": "application/json"
}
params = {
"keyword": company_name,
"pageSize": 1
}
try:
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
data = response.json()
# 使用jsonpath提取核心字段
from jsonpath_ng import parse
expr = parse('$.data.items[*].legalPersonName')
legal_person = [match.value for match in expr.find(data)]
return {
"company_name": data.get("data", {}).get("items", [{}])[0].get("name"),
"legal_person": legal_person[0] if legal_person else None,
"registered_capital": data.get("data", {}).get("items", [{}])[0].get("regCapital")
}
except requests.exceptions.RequestException as e:
print(f"请求失败: {str(e)}")
return None
4.2 司法风险信息查询
def get_judicial_risks(api_key, company_id):
"""
获取企业司法风险信息
:param api_key: API密钥
:param company_id: 企业唯一标识
:return: 风险信息列表
"""
url = f"https://api.tianyancha.com/services/open/ic/v2/company/{company_id}/judicial"
headers = {"X-Auth-Token": api_key}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
risks = []
for item in data.get("data", {}).get("items", []):
risks.append({
"case_type": item.get("caseType"),
"court": item.get("court"),
"case_reason": item.get("caseReason"),
"publish_date": item.get("publishDate")
})
return risks
else:
print(f"错误响应: {response.status_code}")
return []
五、高级功能实现技巧
5.1 批量查询优化
import pandas as pd
from concurrent.futures import ThreadPoolExecutor
def batch_query(api_key, company_names, max_workers=5):
"""
并发批量查询企业信息
:param api_key: API密钥
:param company_names: 企业名称列表
:param max_workers: 最大并发数
:return: 包含查询结果的DataFrame
"""
results = []
def query_single(name):
info = get_company_info(api_key, name)
if info:
results.append(info)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
executor.map(query_single, company_names)
return pd.DataFrame(results)
5.2 数据缓存机制
import pickle
import os
from functools import wraps
def cache_results(cache_dir="./.tianyan_cache"):
"""
查询结果缓存装饰器
:param cache_dir: 缓存目录
"""
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
def decorator(func):
@wraps(func)
def wrapper(api_key, *args, **kwargs):
cache_key = f"{func.__name__}_{'_'.join(map(str, args))}.pkl"
cache_path = os.path.join(cache_dir, cache_key)
if os.path.exists(cache_path):
with open(cache_path, "rb") as f:
return pickle.load(f)
result = func(api_key, *args, **kwargs)
with open(cache_path, "wb") as f:
pickle.dump(result, f)
return result
return wrapper
return decorator
六、最佳实践与注意事项
6.1 频率控制策略
- 基础版API:≤5次/秒
- 专业版API:≤20次/秒
- 实现建议:
```python
import time
class RateLimiter:
def init(self, max_calls, period):
self.max_calls = max_calls
self.period = period
self.call_times = []
def wait(self):
now = time.time()
self.call_times = [t for t in self.call_times if now - t < self.period]
if len(self.call_times) >= self.max_calls:
oldest = self.call_times[0]
sleep_time = self.period - (now - oldest)
if sleep_time > 0:
time.sleep(sleep_time)
self.call_times.append(time.time())
### 6.2 错误处理机制
```python
def handle_api_error(response):
"""
统一API错误处理
:param response: requests响应对象
:return: 错误信息字典或None
"""
if response.status_code == 401:
return {"error": "认证失败", "code": 401}
elif response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", 60))
return {"error": "频率限制", "code": 429, "retry_after": retry_after}
elif response.status_code == 500:
return {"error": "服务端错误", "code": 500}
else:
try:
error_data = response.json()
return {"error": error_data.get("message"), "code": error_data.get("code")}
except ValueError:
return {"error": "未知错误", "code": response.status_code}
七、完整项目示例
# main.py 完整示例
import pandas as pd
from functools import partial
class TianYanChaClient:
def __init__(self, api_key):
self.api_key = api_key
self.rate_limiter = RateLimiter(max_calls=10, period=1)
def query_company(self, company_name):
self.rate_limiter.wait()
return get_company_info(self.api_key, company_name)
def batch_query(self, company_names):
return batch_query(self.api_key, company_names)
# 使用示例
if __name__ == "__main__":
API_KEY = "your_api_key_here"
client = TianYanChaClient(API_KEY)
# 单个查询
company_info = client.query_company("阿里巴巴")
print("单个查询结果:", company_info)
# 批量查询
companies = ["腾讯", "百度", "字节跳动"]
batch_result = client.batch_query(companies)
print("\n批量查询结果:")
print(batch_result.to_markdown(index=False))
八、进阶建议
- 数据清洗:使用pandas的
fillna()
和apply()
方法处理缺失值 - 可视化分析:结合pyecharts生成企业关系图谱
- 定时任务:使用APScheduler实现每日数据更新
- 异常监控:集成Sentry进行错误报警
通过系统化的API调用方案,开发者可以构建高效、稳定的企业信息查询系统。建议从基础版API开始,随着业务需求增长逐步升级到专业版,同时注意遵守天眼查的API使用条款,确保数据获取的合规性。
发表评论
登录后可评论,请前往 登录 或 注册