如何用Python高效查询天眼查企业信息:从API到自动化实践
2025.09.18 16:01浏览量:0简介:本文详解如何使用Python调用天眼查API或模拟操作实现企业信息查询,涵盖接口调用、参数配置、异常处理及数据解析,助力开发者快速构建企业信息检索系统。
如何用Python高效查询天眼查企业信息:从API到自动化实践
一、天眼查企业信息查询的核心价值
天眼查作为国内领先的企业信息查询平台,提供覆盖工商信息、司法风险、经营状况等200+维度的数据服务。对于开发者而言,通过Python实现自动化查询可显著提升效率:
- 批量处理:一次请求获取多家企业核心数据,替代人工逐页检索
- 数据整合:将查询结果与自有系统对接,构建企业画像库
- 实时监控:设置定时任务追踪目标企业动态变化
- 风险预警:自动识别司法涉诉、经营异常等风险信号
典型应用场景包括:金融机构贷前审查、律所尽职调查、供应链企业资质核验、投资机构项目筛选等。
二、Python实现技术路线对比
方案一:调用天眼查官方API(推荐)
优势:数据权威、接口稳定、支持高并发
限制:需申请开发者权限,部分高级字段需付费
实现步骤:
获取API密钥
登录天眼查开发者平台(https://open.tianyancha.com),创建应用获取`AppKey`和`AppSecret`。安装依赖库
pip install requests jsonpath-rw
基础查询示例
import requests
import json
from jsonpath_rw import parse
def query_company_info(company_name, app_key, app_secret):
url = "https://open.api.tianyancha.com/services/open/ic/company/searchV2"
params = {
"keyWord": company_name,
"pageSize": 10,
"appKey": app_key
}
headers = {"X-Tyc-Signature": generate_signature(app_secret)} # 需实现签名算法
response = requests.get(url, params=params, headers=headers)
data = response.json()
# 使用jsonpath提取字段
name_expr = parse("$.data.items[*].name")
names = [match.value for match in name_expr.find(data)]
return names
高级查询技巧
- 使用
/company/detailV2
接口获取完整报告 - 通过
/company/searchRelation
分析企业关联关系 - 结合
/company/changeRecords
追踪工商变更
- 使用
方案二:模拟浏览器操作(备选)
适用场景:无API权限或需查询非开放字段
技术要点:
Selenium自动化
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
def scrape_tianyancha(company_name):
driver = webdriver.Chrome()
driver.get("https://www.tianyancha.com")
# 输入搜索词
search_box = driver.find_element(By.ID, "home-main-search")
search_box.send_keys(company_name)
search_box.submit()
# 解析结果页
time.sleep(2) # 等待加载
company_links = driver.find_elements(By.CSS_SELECTOR, ".search-result-single a")
if company_links:
company_links[0].click()
# 提取详情页数据
name = driver.find_element(By.CSS_SELECTOR, ".company-header-top h1").text
legal_person = driver.find_element(By.XPATH, '//*[@id="_container_baseInfo"]/div[2]/div[1]/div[2]/span').text
return {"name": name, "legal_person": legal_person}
return None
反爬策略应对
- 设置随机User-Agent轮换
- 使用代理IP池(如
requests.get(url, proxies={"http": "http://123.123.123.123:8080"})
) - 控制请求频率(建议QPS≤5)
三、数据解析与存储优化
1. 结构化数据提取
使用jsonpath
或pyquery
精准定位字段:
# 解析API返回的JSON
def parse_company_detail(json_data):
extractor = {
"name": "$.data.name",
"status": "$.data.status",
"reg_capital": "$.data.regCapital",
"legal_person": "$.data.legalPersonName",
"phone": "$.data.contactNumber",
"address": "$.data.registeredAddress"
}
result = {}
for key, path in extractor.items():
expr = parse(path)
matches = expr.find(json_data)
result[key] = matches[0].value if matches else None
return result
2. 数据库存储方案
MySQL方案:适合结构化数据长期存储
CREATE TABLE company_info (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
legal_person VARCHAR(50),
reg_capital DECIMAL(15,2),
status VARCHAR(20),
update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
MongoDB方案:适合非结构化数据快速检索
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["tianyancha_db"]
collection = db["companies"]
# 插入文档
company_doc = {
"name": "腾讯科技",
"legal_person": "马化腾",
"risk_info": {
"lawsuits": 12,
"operating_risks": 3
}
}
collection.insert_one(company_doc)
四、异常处理与性能优化
1. 常见错误处理
try:
response = requests.get(url, timeout=10)
response.raise_for_status() # 检查HTTP错误
data = response.json()
if data.get("code") != 0: # 天眼查自定义错误码
raise Exception(f"API错误: {data.get('message')}")
except requests.exceptions.RequestException as e:
print(f"请求失败: {str(e)}")
except json.JSONDecodeError:
print("返回数据非JSON格式")
2. 性能提升技巧
并发请求:使用
asyncio
或gevent
实现异步调用import asyncio
import aiohttp
async def fetch_company(session, name):
url = f"https://open.api.tianyancha.com/...?name={name}"
async with session.get(url) as response:
return await response.json()
async def main():
async with aiohttp.ClientSession() as session:
tasks = [fetch_company(session, "阿里"+str(i)) for i in range(5)]
results = await asyncio.gather(*tasks)
print(results)
缓存机制:对重复查询结果进行本地缓存
import pickle
import os
CACHE_FILE = "tianyancha_cache.pkl"
def get_cached_data(company_name):
if os.path.exists(CACHE_FILE):
with open(CACHE_FILE, "rb") as f:
cache = pickle.load(f)
return cache.get(company_name)
return None
def save_to_cache(company_name, data):
cache = {}
if os.path.exists(CACHE_FILE):
with open(CACHE_FILE, "rb") as f:
cache = pickle.load(f)
cache[company_name] = data
with open(CACHE_FILE, "wb") as f:
pickle.dump(cache, f)
五、合规与安全注意事项
六、进阶应用场景
1. 企业关系图谱构建
通过/company/searchRelation
接口获取股东、投资、任职等关系数据,使用networkx
库可视化:
import networkx as nx
import matplotlib.pyplot as plt
def build_relation_graph(company_id):
G = nx.Graph()
# 假设已获取关系数据
relations = [
{"from": "腾讯", "to": "马化腾", "type": "legal_person"},
{"from": "腾讯", "to": "南非MIH", "type": "shareholder"}
]
for rel in relations:
G.add_edge(rel["from"], rel["to"], relation=rel["type"])
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_size=3000)
plt.show()
2. 实时监控系统
结合APScheduler
实现定时查询:
from apscheduler.schedulers.blocking import BlockingScheduler
def monitor_company(company_id):
# 查询企业最新状态
new_data = query_company_detail(company_id)
# 与历史数据对比
# 触发预警逻辑...
scheduler = BlockingScheduler()
scheduler.add_job(monitor_company, 'interval', hours=12, args=['123456'])
scheduler.start()
七、总结与建议
- 优先使用API:官方接口在稳定性、数据完整性上具有明显优势
- 建立错误重试机制:网络波动时自动重试3次
- 模块化设计:将查询、解析、存储功能分离,便于维护
- 关注接口更新:定期检查天眼查API文档变更
通过Python实现天眼查企业信息查询,开发者可构建起高效、可靠的企业数据采集系统。实际开发中,建议从简单查询开始,逐步扩展至复杂场景,同时始终将合规性放在首位。
发表评论
登录后可评论,请前往 登录 或 注册