第一次 API 请求

这篇只完成一次普通 HTML GET,验证请求是否真实运行、目标路径是否保留,以及返回内容是否符合预期。不是全站采集器,也不会自动升级接口。

  1. 1. 读取安全变量Key 与目标 URL
  2. 2. 映射 API 请求保留路径和查询
  3. 3. 检查状态与类型不自动重定向
  4. 4. 提取标题失败立即停止

1. 完成安全配置

按 API Key 安全配置教程准备环境、requests 依赖与 TARGET_URL

2. 保存完整请求文件

将下面代码保存为 cloudbypass_first_request.py。V1 用于这次普通页面测试;API 入口替换主机,目标的路径和查询保留,目标主机通过 x-cb-host 传入。

"""One V1 HTML request. Configure credentials locally; never print request headers."""
import os
from html.parser import HTMLParser
from urllib.parse import urlsplit, urlunsplit

import requests


class PageTitle(HTMLParser):
    def __init__(self):
        super().__init__()
        self.inside = False
        self.parts = []

    def handle_starttag(self, tag, attrs):
        if tag.lower() == 'title':
            self.inside = True

    def handle_endtag(self, tag):
        if tag.lower() == 'title':
            self.inside = False

    def handle_data(self, data):
        if self.inside:
            self.parts.append(data)


def required(name):
    value = os.environ.get(name, '').strip()
    if not value:
        raise ValueError(f'Set {name} in the actual runtime; do not share its value in chat.')
    return value


def main():
    target = urlsplit(required('TARGET_URL'))
    if target.scheme not in ('http', 'https') or not target.hostname or target.username or target.password:
        raise ValueError('Use a complete HTTP(S) URL without embedded credentials.')
    api_url = urlunsplit(('https', 'api.cloudbypass.com', target.path or '/', target.query, ''))
    headers = {
        'x-cb-apikey': required('CLOUDBYPASS_APIKEY'),
        'x-cb-host': target.netloc,
        'x-cb-protocol': target.scheme,
        'x-cb-timeout': '60',
    }
    with requests.get(api_url, headers=headers, timeout=(15, 90), allow_redirects=False, stream=True) as response:
        if response.headers.get('x-cb-status', '').lower() != 'ok':
            raise RuntimeError(f'API success not confirmed; HTTP {response.status_code}. Inspect redacted code/message locally.')
        if not 200 <= response.status_code < 300:
            raise RuntimeError(f'Target returned HTTP {response.status_code}; do not retry automatically.')
        if 'text/html' not in response.headers.get('Content-Type', '').lower():
            raise RuntimeError('Expected HTML. Check the target and required output format.')
        body = bytearray()
        for chunk in response.iter_content(chunk_size=8192):
            body.extend(chunk)
            if len(body) > 262144:
                raise RuntimeError('HTML exceeds this starter example limit; adapt the reader before continuing.')
        parser = PageTitle()
        parser.feed(body.decode(response.encoding or 'utf-8', errors='replace'))
        print('HTTP:', response.status_code, '| Cloudbypass:', response.headers['x-cb-status'])
        print('Title:', ' '.join(''.join(parser.parts).split()) or '(no title found)')


if __name__ == '__main__':
    try:
        main()
    except requests.RequestException as error:
        raise SystemExit(f'Network request failed ({type(error).__name__}); inspect redacted diagnostics locally.')

3. 手动执行一次

Windows 使用虚拟环境的解释器;macOS/Linux 使用对应路径。真实请求可能计费,执行前确认 URL 和一次尝试预算。

.\.venv\Scripts\python.exe cloudbypass_first_request.py
./.venv/bin/python cloudbypass_first_request.py

4. 检查而不是猜测结果

  • 成功路径会打印 HTTP、Cloudbypass 状态和页面标题;这是预期输出项目,不是替你完成了线上测试。
  • example.com 的页面标题通常可用于对照;改用你的目标时核对你自己的业务字段。
  • 出现登录页、错误页、空标题或不符合类型的结果,应停止并排查,不用模型编造缺失字段。
  • 256 KiB 是本篇入门代码的读取上限,不是产品大小限制。

常见问题

目标有路径和端口怎么填?

TARGET_URL 填完整 URL。代码保留路径、查询和目标端口,片段 # 不发送到服务器。

需要 V2 时直接改一行就行吗?

不够。先根据目标响应确认需求,再按文档补充稳定代理和会话参数,本篇不自动升级。

网络失败是否会泄露密钥?

此代码只输出网络异常类型,不打印完整请求或异常中的请求头;你自己的日志也要按同样原则检查。

继续阅读

官方 Vibe Coding 工具接入文档