SuperAPI AI Directory

china-law-search

Data & analytics

View repository

Updated 10-15 22:09

About this skill

Unified Query of Chinese Laws and Regulations

Unified query entry point, automatically queries the China National Laws and Regulations Database (flk.npc.gov.cn) first, and falls back to the National Regulations Database (gov.cn) if not found.

Coverage:

  • China National Laws and Regulations Database: Constitution, laws, administrative regulations, local regulations, judicial interpretations, supervisory regulations
  • National Regulations Database: departmental rules, local government rules

When to Use

  • Query whether a certain law, regulation, or rule is still in effect
  • Search for laws, regulations, or rules related to a keyword
  • Find newly issued laws and regulations after a certain date
  • Batch check the current status of a set of regulations (automatic dual-database joint query)
  • Read a regulation list from Excel, batch check validity, and output Excel results
  • Query newly issued regulations and directly output Excel
  • Batch download full texts of regulations (docx)
  • Download full texts of regulations (docx/pdf)

Usage

Python API (recommended usage for AI Agents)

import sys, os
sys.path.insert(0, os.path.expanduser("~/.claude/skills/china-law-search/scripts"))
import law_search

# ── 搜索 ──
result = law_search.unified_search("安全生产法")
result = law_search.unified_search("危险化学品 安全管理", content_search=True)

# ── 批量检查 ──
results = law_search.unified_batch_check(["法规名称1", "法规名称2"])

# ── 从Excel批量检查并输出Excel(一步到位,支持断点续查)──
law_search.batch_check_to_excel(
    input_excel="法律法规清单.xlsx",
    output_excel="法规有效性查询结果.xlsx",
    col="B",              # 法规名称所在列
    start_row=2,           # 数据起始行(跳过表头)
    progress_file="check_progress.json",  # 断点续查进度文件
)

# ── 查询新发布法规并输出Excel ──
law_search.new_since_to_excel("2026-01-01", "2026年新发布法规.xlsx")

# ── 批量下载法规全文(推荐工作流:查询→转格式→下载→重试)──
import json

# Step 1: 批量查询
results = law_search.unified_batch_check(["法规名称1", "法规名称2"])

# Step 2: 转成 batch_download_from_check 需要的格式
check_progress = {}
for r in results:
    name = r.get("name", "")
    check_progress[name] = {
        "status": r.get("status", ""),
        "url": r.get("url", ""),
        "source": "国家规章库" if r.get("source") == "gov.cn" else "国家法律法规数据库",
    }

# Step 3: 批量下载(支持断点续下)
law_search.batch_download_from_check(
    check_progress=check_progress,
    output_dir="./下载",
    delay=0.5,
    dl_progress_file="download_progress.json",
)

# Step 4: 如有超时,直接重跑(自动跳过已下载的)
law_search.batch_download_from_check(
    check_progress=check_progress,
    output_dir="./下载",
    delay=0.5,
    dl_progress_file="download_progress.json",
)

# ── 单独调用某个库 ──
from lib import flk_api, gov_api

flk_api.search("安全生产法", exact=True)
flk_api.search("危险化学品", content_search=True)
flk_api.search_all_pages("消防安全", content_search=True)

gov_api.search("商品房屋租赁管理办法")
gov_api.search("消防安全", content_search=True)

# 下载
flk_api.download_file("bbbs_id", output_dir="./downloads")
gov_api.download_as_docx("商品房屋租赁管理办法", output_dir="./downloads")

CLI

LAW=~/.claude/skills/china-law-search/scripts/law_search.py

# ── 搜索 ──
python3 $LAW search "安全生产法"
python3 $LAW search "安全生产法" --exact
python3 $LAW search "危险化学品 安全管理" --content
python3 $LAW search "消防安全" --content --all-pages

# ── 批量检查 ──
python3 $LAW batch-check laws.txt
python3 $LAW batch-check laws.txt --json

# ── 从Excel批量检查并输出Excel ──
python3 $LAW check-excel 法律法规清单.xlsx -o 查询结果.xlsx --col B --progress progress.json

# ── 查询新发布法规并输出Excel ──
python3 $LAW new-since-excel 2026-01-01 -o 2026年新发布法规.xlsx

# ── 查找新发布法规(文本输出)──
python3 $LAW new-since 2025-03-09
python3 $LAW new-since 2025-03-09 --all-types --all-pages --json

# ── 下载 ──
python3 $LAW download <bbbs_id> --output ./downloads
python3 $LAW batch-download check_result.json --output ./downloads

# ── 从检查进度批量下载 ──
python3 $LAW download-from-check progress.json -o ./下载 --dl-progress dl_progress.json

File Structure

china-law-search/
├── SKILL.md                    # 本文件
├── scripts/
│   ├── law_search.py           # 统一入口(推荐使用)
│   └── flk_api.py              # flk.npc.gov.cn 独立客户端(向后兼容)
└── lib/
    ├── __init__.py
    ├── flk_api.py              # 国家法律法规数据库 API
    ├── gov_api.py              # 国家规章库 API
    ├── refresh_gov_key.js      # playwright-cli 刷新 athenaappkey 脚本
    └── .athena_key_cache.json  # athenaappkey 缓存(自动生成)

Overview of Core Functions

Function Purpose Input Output
unified_search() Unified search (two databases) Keyword dict
unified_batch_check() Batch status check Name list list
batch_check_to_excel() Excel→batch check→Excel Input Excel path Output Excel
new_since_to_excel() Newly issued regulations→Excel Date Excel file
unified_new_since() Newly issued regulation query Date dict
batch_download_from_check() Batch download full texts Check progress dict Download progress dict

Output Field Descriptions

All query results uniformly include the following fields:

Field Description
title Regulation name
type / flxz Regulation category (law/administrative regulation/departmental rule/local government rule, etc.)
date / gbrq Publication date
status / sxx_text Status (in effect/amended/repealed/not yet effective)
org / zdjgName Enacting authority
source Data source:国家法律法规数据库 or 国家规章库
url Original text link (clickable)

File Download

China National Laws and Regulations Database (flk)

  • Directly download official docx/pdf files, obtained from OSS via signed URLs
  • flk has JS anti-scraping protection,download_file() internally bypassed by obtaining signed URLs through playwright-cli

National Regulations Database (gov.cn)

  • The regulations database has no direct file download interface
  • By scraping the detail page HTML and using pandoc to convert to docx (preserving the original format)
  • Dependencies: requires installation of pandoc(brew install pandoc) and python-docx(pip install python-docx)

Batch Download

  • batch_download_from_check() Batch download from check progress data
  • Automatically distinguishes between flk and the regulations database, using different download methods
  • Supports resumable downloads (via the dl_progress_file parameter)

athenaappkey management

The National Regulations Database API requires a dynamic authentication key, which expires in about 1 hour.

Automatic refresh

gov_api.py When an expired or invalid key is detected, it will automatically intercept browser requests via playwright-cli to obtain a new key, and cache it only after verifying its validity. Process:

  1. Use playwright-cli open to open the regulations database page
  2. Use playwright-cli --raw run-code to intercept the athena/forward request and extract athenaappkey header
  3. Send a test request to verify the key's validity (resultCode.code == 200)
  4. After verification passes, save to cache and close the browser

If automatic refresh fails (playwright-cli unavailable or network issues), you can manually obtain it according to the "athenaappkey refresh standard process" below.

File naming rules

Downloaded file naming: 法规类型_法规名称_公布日期_状态.ext For example: 法律_中华人民共和国安全生产法_2021-06-10_有效.docx

Known issues and experience

flk download timeout and retry

  • The download API of flk.npc.gov.cn has JS anti-scraping protection; direct HTTP requests will return HTML instead of JSON
  • Solution:flk_api.download_file() Internally obtains the signed download URL via playwright-cli
  • If playwright-cli is unavailable, the download will fail
  • Intermittent timeouts may occur during batch downloads (The read operation timed out), which is triggered by flk's anti-scraping
  • batch_download_from_check() Supports resumable downloads; rerunning timed-out items will automatically skip completed ones
  • It is recommended to keep the delay at 0.5-1 second for batch downloads, and if there is a timeout, just rerun it

Regulations database API return format changes (discovered 2026-04)

  • The return structure of the regulations database search API may have two formats:
    • Old format:result.data is a dict, containing pager and list
    • New format:result.data is a list (directly the result list),result.totalCount and result.pageSize are at the upper level
  • gov_api.py 's search() and search_with_content() are already compatible with both formats
  • When athenaappkey is invalid, the API will not return an HTTP error, but will return data: [] + resultCode containing error information (such as athena_01503 解密失败)
  • If the regulations database returns 0 results but there should actually be data, first check whether athenaappkey is valid

Regulations database athenaappkey expired

  • The athenaappkey of the regulations database API expires in about 1 hour
  • gov_api.py Has been improved to automatic refresh + verification: when the key is expired or invalid, automatically intercept requests via playwright-cli to obtain a new key, and verify its validity
  • Automatic refresh depends on playwright-cli (@playwright/cli), and if not installed, it will automatically install via npm install -g @playwright/cli installation
  • If automatic refresh fails (such as when playwright-cli is unavailable), you can manually obtain it according to the "athenaappkey refresh standard process"

athenaappkey refresh standard process (3 steps)

Step 1: Open the regulations database page

playwright-cli open https://www.gov.cn/zhengce/xxgk/gjgzk/index.htm

Step 2: Intercept requests to obtain the key

playwright-cli --raw run-code "async page => {
  const keys = [];
  await page.route(url => url.href.includes('athena/forward'), async route => {
    const key = route.request().headers()['athenaappkey'] || '';
    if (key) keys.push(key);
    await route.continue();
  });
  await page.reload({ waitUntil: 'networkidle' });
  await page.waitForTimeout(3000);
  await page.unroute(url => url.href.includes('athena/forward'));
  return keys.join(',');
}"

The output is multiple comma-separated keys (all the same); just take the first one.

Step 3: Save to the cache file

import json, time, os
key = '这里粘贴Step2输出的第一个key'
cache_path = os.path.expanduser('~/.claude/skills/china-law-search/lib/.athena_key_cache.json')
with open(cache_path, 'w') as f:
    json.dump({'key': key, 'ts': time.time()}, f)

Step 4: Close the browser

playwright-cli close

After refresh, the cache is valid for about 1 hour, enough to complete most batch operations.

Some regulations cannot be found in either database

  • Normative documents such as notices, opinions, and guidelines are not included in either database
  • Internal management measures related to central enterprises are usually not in public regulatory databases (for example, the "Central Enterprise Compliance Management Measures" can be found in the regulations database, but the "Guidelines for Comprehensive Risk Management of Central Enterprises" cannot be found)
  • Specific types that cannot be found: "guidelines", "opinions", "notices", "work rules", and "work provisions" issued by SASAC
  • Such documents are marked as "not found" and need to be obtained from the SASAC official website or other channels

Batch operation recommendations

  • For large batch queries (>100 items), it is recommended to use batch_check_to_excel() and specify progress_file
  • The progress file supports resuming interrupted queries; after an interruption, rerunning will skip completed items
  • The same applies to downloads; use dl_progress_file to support resuming interrupted downloads
  • It is recommended to leave an interval of 0.5-1 second between queries and downloads, and if there is a timeout, just rerun directly (resume interrupted downloads)
  • If there is a timeout during batch downloads, just rerun (completed items are automatically skipped)

unified_batch_check return format

  • Returns a list, each element is a dict, containing name, found, title, status, bbbs, url, flxz, source and other fields
  • found=True When there is complete information,found=False when there is only name and status
  • To pass to batch_download_from_check(), it needs to be converted to {法规名: {status, url, source, ...}} format dict
  • Note:unified_batch_check returned status field for regulations database results is "有效(规章库)",source is "gov.cn"

flk_api.search return format

  • Returns a dict (not a list), with the structure {"total": N, "rows": [...]}
  • Each row contains bbbs(ID)、title、gbrq、sxx(timeliness code),flxz(regulation category), etc.
  • Note:gbrq field may be None(not an empty string), and the None value needs to be handled when comparing
  • Search results may include irrelevant regulations (for example, searching "constitution" will return "Xiamen City... decision on... constitution..."),batch_check() already has exact matching logic internally,do not write your own matching logic, directly use unified_batch_check

Key Rules

  • During batch checks, the two databases are automatically queried together: first query flk, and if not found, then query the regulations database
  • The flk API requires no authentication and is stable and reliable
  • The regulations database API requires a dynamic athenaappkey; after expiration, it will automatically refresh and verify through playwright-cli, usually without manual intervention. If automatic refresh fails, obtain it manually according to the "athenaappkey refresh standard process"
  • It is recommended to leave an interval of 0.5-1 second between queries and downloads
  • The National Regulations Database only includes currently effective regulations; repealed ones are not in the database
  • Some normative documents (notices, opinions, guidelines, etc.) are not included in either database and require manual confirmation
  • --content Searches by body text content, supported by both databases
  • --all-pages Automatically paginates to obtain all results, suitable for scenarios with many results
  • For full-text search, it is recommended to use short keywords (2-4 words); long sentences may return no results
  • Regulations database downloads work by scraping the detail page HTML and converting it to docx with pandoc; pandoc needs to be installed
  • Excel output uses openpyxl, which needs to be installed (pip install openpyxl)
  • Do not write your own regulation matching logic, directly use unified_batch_check(), it already handles edge cases internally such as exact matching, multi-version selection, and None values
  • Do not write your own download logic, use batch_download_from_check() combined with unified_batch_check() results, it automatically distinguishes between flk/regulation library and supports resumable downloads
  • If batch downloads time out, just rerun (completed ones are automatically skipped, resumable download)

Self-Evolution Rules

After using this skill to complete a task, if the following situations are found, the skill code and documentation should be automatically updated:

  1. New API changes: If the API interfaces of flk or the regulation library change (return format, URL, authentication method, etc.), update the corresponding lib/flk_api.py or lib/gov_api.py
  2. New usage patterns: If the user's way of using it produces new useful functions or workflows, integrate them into scripts/law_search.py and update SKILL.md
  3. Bug fixes: If a bug is found and fixed during use, ensure the fix is persisted to the skill file
  4. Experience accumulation: If new known issues or solutions are encountered, update the "Known Issues and Experience" section of SKILL.md
  5. Dependency changes: If new dependency requirements or dependency version issues are found, update the documentation

Follow these principles when updating:

  • Maintain backward compatibility and do not break existing APIs
  • New functions should provide both a Python API and a CLI interface
  • All batch operations should support resuming (via a progress file)
  • Update the function list and usage examples in SKILL.md

Author: nigo WeChat Official Account: 逆行的狗