logo

如何用Python高效查询天眼查企业信息:从API到自动化实践

作者:php是最好的2025.09.18 16:01浏览量:0

简介:本文详解如何使用Python调用天眼查API或模拟操作实现企业信息查询,涵盖接口调用、参数配置、异常处理及数据解析,助力开发者快速构建企业信息检索系统。

如何用Python高效查询天眼查企业信息:从API到自动化实践

一、天眼查企业信息查询的核心价值

天眼查作为国内领先的企业信息查询平台,提供覆盖工商信息、司法风险、经营状况等200+维度的数据服务。对于开发者而言,通过Python实现自动化查询可显著提升效率:

  1. 批量处理:一次请求获取多家企业核心数据,替代人工逐页检索
  2. 数据整合:将查询结果与自有系统对接,构建企业画像库
  3. 实时监控:设置定时任务追踪目标企业动态变化
  4. 风险预警:自动识别司法涉诉、经营异常等风险信号

典型应用场景包括:金融机构贷前审查、律所尽职调查、供应链企业资质核验、投资机构项目筛选等。

二、Python实现技术路线对比

方案一:调用天眼查官方API(推荐)

优势:数据权威、接口稳定、支持高并发
限制:需申请开发者权限,部分高级字段需付费
实现步骤

  1. 获取API密钥
    登录天眼查开发者平台(https://open.tianyancha.com),创建应用获取`AppKey`和`AppSecret`。

  2. 安装依赖库

    1. pip install requests jsonpath-rw
  3. 基础查询示例

    1. import requests
    2. import json
    3. from jsonpath_rw import parse
    4. def query_company_info(company_name, app_key, app_secret):
    5. url = "https://open.api.tianyancha.com/services/open/ic/company/searchV2"
    6. params = {
    7. "keyWord": company_name,
    8. "pageSize": 10,
    9. "appKey": app_key
    10. }
    11. headers = {"X-Tyc-Signature": generate_signature(app_secret)} # 需实现签名算法
    12. response = requests.get(url, params=params, headers=headers)
    13. data = response.json()
    14. # 使用jsonpath提取字段
    15. name_expr = parse("$.data.items[*].name")
    16. names = [match.value for match in name_expr.find(data)]
    17. return names
  4. 高级查询技巧

    • 使用/company/detailV2接口获取完整报告
    • 通过/company/searchRelation分析企业关联关系
    • 结合/company/changeRecords追踪工商变更

方案二:模拟浏览器操作(备选)

适用场景:无API权限或需查询非开放字段
技术要点

  1. Selenium自动化

    1. from selenium import webdriver
    2. from selenium.webdriver.common.by import By
    3. import time
    4. def scrape_tianyancha(company_name):
    5. driver = webdriver.Chrome()
    6. driver.get("https://www.tianyancha.com")
    7. # 输入搜索词
    8. search_box = driver.find_element(By.ID, "home-main-search")
    9. search_box.send_keys(company_name)
    10. search_box.submit()
    11. # 解析结果页
    12. time.sleep(2) # 等待加载
    13. company_links = driver.find_elements(By.CSS_SELECTOR, ".search-result-single a")
    14. if company_links:
    15. company_links[0].click()
    16. # 提取详情页数据
    17. name = driver.find_element(By.CSS_SELECTOR, ".company-header-top h1").text
    18. legal_person = driver.find_element(By.XPATH, '//*[@id="_container_baseInfo"]/div[2]/div[1]/div[2]/span').text
    19. return {"name": name, "legal_person": legal_person}
    20. return None
  2. 反爬策略应对

    • 设置随机User-Agent轮换
    • 使用代理IP池(如requests.get(url, proxies={"http": "http://123.123.123.123:8080"})
    • 控制请求频率(建议QPS≤5)

三、数据解析与存储优化

1. 结构化数据提取

使用jsonpathpyquery精准定位字段:

  1. # 解析API返回的JSON
  2. def parse_company_detail(json_data):
  3. extractor = {
  4. "name": "$.data.name",
  5. "status": "$.data.status",
  6. "reg_capital": "$.data.regCapital",
  7. "legal_person": "$.data.legalPersonName",
  8. "phone": "$.data.contactNumber",
  9. "address": "$.data.registeredAddress"
  10. }
  11. result = {}
  12. for key, path in extractor.items():
  13. expr = parse(path)
  14. matches = expr.find(json_data)
  15. result[key] = matches[0].value if matches else None
  16. return result

2. 数据库存储方案

  • MySQL方案:适合结构化数据长期存储

    1. CREATE TABLE company_info (
    2. id INT AUTO_INCREMENT PRIMARY KEY,
    3. name VARCHAR(100) NOT NULL,
    4. legal_person VARCHAR(50),
    5. reg_capital DECIMAL(15,2),
    6. status VARCHAR(20),
    7. update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    8. );
  • MongoDB方案:适合非结构化数据快速检索

    1. from pymongo import MongoClient
    2. client = MongoClient("mongodb://localhost:27017/")
    3. db = client["tianyancha_db"]
    4. collection = db["companies"]
    5. # 插入文档
    6. company_doc = {
    7. "name": "腾讯科技",
    8. "legal_person": "马化腾",
    9. "risk_info": {
    10. "lawsuits": 12,
    11. "operating_risks": 3
    12. }
    13. }
    14. collection.insert_one(company_doc)

四、异常处理与性能优化

1. 常见错误处理

  1. try:
  2. response = requests.get(url, timeout=10)
  3. response.raise_for_status() # 检查HTTP错误
  4. data = response.json()
  5. if data.get("code") != 0: # 天眼查自定义错误码
  6. raise Exception(f"API错误: {data.get('message')}")
  7. except requests.exceptions.RequestException as e:
  8. print(f"请求失败: {str(e)}")
  9. except json.JSONDecodeError:
  10. print("返回数据非JSON格式")

2. 性能提升技巧

  • 并发请求:使用asynciogevent实现异步调用

    1. import asyncio
    2. import aiohttp
    3. async def fetch_company(session, name):
    4. url = f"https://open.api.tianyancha.com/...?name={name}"
    5. async with session.get(url) as response:
    6. return await response.json()
    7. async def main():
    8. async with aiohttp.ClientSession() as session:
    9. tasks = [fetch_company(session, "阿里"+str(i)) for i in range(5)]
    10. results = await asyncio.gather(*tasks)
    11. print(results)
  • 缓存机制:对重复查询结果进行本地缓存

    1. import pickle
    2. import os
    3. CACHE_FILE = "tianyancha_cache.pkl"
    4. def get_cached_data(company_name):
    5. if os.path.exists(CACHE_FILE):
    6. with open(CACHE_FILE, "rb") as f:
    7. cache = pickle.load(f)
    8. return cache.get(company_name)
    9. return None
    10. def save_to_cache(company_name, data):
    11. cache = {}
    12. if os.path.exists(CACHE_FILE):
    13. with open(CACHE_FILE, "rb") as f:
    14. cache = pickle.load(f)
    15. cache[company_name] = data
    16. with open(CACHE_FILE, "wb") as f:
    17. pickle.dump(cache, f)

五、合规与安全注意事项

  1. 遵守服务条款:禁止爬取付费字段或进行大规模数据抓取
  2. 数据脱敏处理:对获取的手机号、邮箱等敏感信息进行加密存储
  3. 频率控制:建议单IP每日查询量不超过2000次
  4. 日志记录:完整记录查询操作,便于问题追溯

六、进阶应用场景

1. 企业关系图谱构建

通过/company/searchRelation接口获取股东、投资、任职等关系数据,使用networkx库可视化:

  1. import networkx as nx
  2. import matplotlib.pyplot as plt
  3. def build_relation_graph(company_id):
  4. G = nx.Graph()
  5. # 假设已获取关系数据
  6. relations = [
  7. {"from": "腾讯", "to": "马化腾", "type": "legal_person"},
  8. {"from": "腾讯", "to": "南非MIH", "type": "shareholder"}
  9. ]
  10. for rel in relations:
  11. G.add_edge(rel["from"], rel["to"], relation=rel["type"])
  12. pos = nx.spring_layout(G)
  13. nx.draw(G, pos, with_labels=True, node_size=3000)
  14. plt.show()

2. 实时监控系统

结合APScheduler实现定时查询:

  1. from apscheduler.schedulers.blocking import BlockingScheduler
  2. def monitor_company(company_id):
  3. # 查询企业最新状态
  4. new_data = query_company_detail(company_id)
  5. # 与历史数据对比
  6. # 触发预警逻辑...
  7. scheduler = BlockingScheduler()
  8. scheduler.add_job(monitor_company, 'interval', hours=12, args=['123456'])
  9. scheduler.start()

七、总结与建议

  1. 优先使用API:官方接口在稳定性、数据完整性上具有明显优势
  2. 建立错误重试机制网络波动时自动重试3次
  3. 模块化设计:将查询、解析、存储功能分离,便于维护
  4. 关注接口更新:定期检查天眼查API文档变更

通过Python实现天眼查企业信息查询,开发者可构建起高效、可靠的企业数据采集系统。实际开发中,建议从简单查询开始,逐步扩展至复杂场景,同时始终将合规性放在首位。

相关文章推荐

发表评论