Files
yilv 565fad946f feat: 添加 iTick Python SDK 初始版本
- 实现 REST API 客户端,支持股票、加密货币、外汇、期货、基金和指数数据
- 实现 WebSocket 客户端,支持实时数据订阅
- 添加异常处理、工具函数和常量定义
- 包含安装配置和示例代码
- 添加文档爬虫工具用于生成离线文档
2026-03-03 15:26:09 +08:00

272 lines
9.2 KiB
Python

import requests
from bs4 import BeautifulSoup
from markdownify import markdownify as md
import os
import time
from urllib.parse import urljoin, urlparse
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
BASE_URL = "https://docs.itick.org/zh-cn"
OUTPUT_DIR = "docs"
def setup():
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
def get_session():
session = requests.Session()
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
def get_soup(url, session=None):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
try:
if session:
response = session.get(url, headers=headers, timeout=10)
else:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
return BeautifulSoup(response.content, "lxml")
except Exception as e:
print(f"Error fetching {url}: {e}")
return None
def process_html(soup):
# 1. 提取正文
# 尝试找到包含文章内容的容器
article = soup.select_one('article.container')
if not article:
article = soup.select_one('main.section')
if not article:
return soup.body
# 2. 清理无关元素
for selector in [
'aside',
'.bread-crumbs',
'.select-key-box',
'footer',
'.surroundList', # 底部导航
'style',
'script',
'.text-hidden', # 隐藏的 SEO 标题
'.code-title', # 复制代码按钮
'.response-result-title-btns', # 响应结果切换按钮
'.response-result-title-info', # 响应结果复制按钮
'.iconfont.icon-copy' # 所有的复制图标
]:
for tag in article.select(selector):
tag.decompose()
# 3. 转换参数列表为表格 (.query-params)
for params_box in article.select('.query-params'):
table = soup.new_tag('table')
# Thead
thead = soup.new_tag('thead')
tr = soup.new_tag('tr')
headers = ['参数名', '类型', '必填', '说明']
for h in headers:
th = soup.new_tag('th')
th.string = h
tr.append(th)
thead.append(tr)
table.append(thead)
# Tbody
tbody = soup.new_tag('tbody')
fields = params_box.select('.custom-field')
if not fields:
continue
for field in fields:
tr = soup.new_tag('tr')
# Name
name_el = field.select_one('.field-name')
td_name = soup.new_tag('td')
td_name.string = name_el.get_text(strip=True) if name_el else ''
tr.append(td_name)
# Type
type_el = field.select_one('.field-type')
td_type = soup.new_tag('td')
td_type.string = type_el.get_text(strip=True) if type_el else ''
tr.append(td_type)
# Required
req_el = field.select_one('.field-required')
td_req = soup.new_tag('td')
td_req.string = req_el.get_text(strip=True) if req_el else ''
tr.append(td_req)
# Description
desc_el = field.select_one('.field-content')
td_desc = soup.new_tag('td')
desc_text = ""
if desc_el:
desc_text = desc_el.get_text(strip=True)
# 检查 dropdown options
select_box = field.select_one('.custom-select')
if select_box:
options = [opt.get_text(strip=True) for opt in select_box.select('.custom-option span')]
# 去重
options = list(dict.fromkeys(options))
if options:
desc_text += f" (可选值: {', '.join(options)})"
td_desc.string = desc_text
tr.append(td_desc)
tbody.append(tr)
table.append(tbody)
params_box.replace_with(table)
# 3.5 转换响应参数为表格
for header in article.find_all(['h2', 'h3']):
if "响应参数" in header.get_text():
content_div = header.find_next_sibling('div')
if content_div and content_div.select('.custom-field'):
table = soup.new_tag('table')
thead = soup.new_tag('thead')
tr = soup.new_tag('tr')
for h in ['参数名', '类型', '说明']:
th = soup.new_tag('th')
th.string = h
tr.append(th)
thead.append(tr)
table.append(thead)
tbody = soup.new_tag('tbody')
for field in content_div.select('.custom-field'):
tr = soup.new_tag('tr')
name_el = field.select_one('.field-name')
td_name = soup.new_tag('td')
td_name.string = name_el.get_text(strip=True) if name_el else ''
tr.append(td_name)
type_el = field.select_one('.field-type')
td_type = soup.new_tag('td')
td_type.string = type_el.get_text(strip=True) if type_el else ''
tr.append(td_type)
desc_el = field.select_one('.field-content')
td_desc = soup.new_tag('td')
td_desc.string = desc_el.get_text(strip=True) if desc_el else ''
tr.append(td_desc)
tbody.append(tr)
table.append(tbody)
content_div.replace_with(table)
# 4. 转换查询 URL 盒子 (.query-box)
for query_box in article.select('.query-box'):
method = query_box.select_one('.method')
url = query_box.select_one('.url')
if method and url:
# 使用 pre code 块展示
code_block = soup.new_tag('pre')
code = soup.new_tag('code')
code.string = f"{method.get_text(strip=True)} {url.get_text(strip=True)}"
code_block.append(code)
query_box.replace_with(code_block)
# 5. 处理响应结果区域 (.response-result)
# 移除多余的容器,只保留代码块
for resp_box in article.select('.response-result'):
content = resp_box.select_one('.response-result-content')
if content:
# 直接把 content 里的 pre 拿出来,替换整个 box
pre = content.select_one('pre')
if pre:
resp_box.replace_with(pre)
else:
resp_box.replace_with(content)
return article
def main():
setup()
session = get_session()
print(f"Fetching {BASE_URL}...")
soup = get_soup(BASE_URL, session)
if not soup:
return
# Extract all documentation links from the sidebar
links = []
sidebar = soup.select_one('aside.menu-box')
if sidebar:
for a in sidebar.select('a.menu-item'):
href = a.get('href')
if href and not href.startswith('http') and not href.startswith('#'):
full_url = urljoin(BASE_URL, href)
# Ensure we only crawl the docs part and not external links
if '/zh-cn' in full_url:
links.append(full_url)
# Remove duplicates
links = list(set(links))
print(f"Found {len(links)} pages to crawl.")
# Crawl each page
for i, link in enumerate(links):
print(f"[{i+1}/{len(links)}] Crawling {link}...")
page_soup = get_soup(link, session)
if not page_soup:
continue
# Process and optimize HTML
content_html = process_html(page_soup)
if content_html:
# Convert to Markdown
markdown = md(str(content_html), heading_style="ATX", strip=['script', 'style'])
# Post-processing markdown
# Remove multiple newlines
while '\n\n\n' in markdown:
markdown = markdown.replace('\n\n\n', '\n\n')
# Save to file
parsed_url = urlparse(link)
path = parsed_url.path.strip('/')
if path.startswith('zh-cn/'):
path = path[6:] # Remove 'zh-cn/' prefix
if not path:
path = "index"
file_path = os.path.join(OUTPUT_DIR, f"{path}.md")
# Ensure directory exists
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, "w", encoding="utf-8") as f:
f.write(f"# Source: {link}\n\n")
f.write(markdown)
print(f"Saved to {file_path}")
# Be nice to the server
time.sleep(0.5)
print("Crawling completed.")
if __name__ == "__main__":
main()