首页 / 文档 / 特殊站点处理

特殊站点处理

抖音热搜

抖音接口需要先访问 login.douyin.com 获取 Cookie,否则直接 403。

Aneiang.Pa 内置 DouYinCookieMiddleware,自动处理:

var data = await Pa.Source("DouYin").GetAsync();  // 零配置

实测输出:

[DouYinCookie] 已获取 Cookie(114 字节,10 分钟内复用)
成功!共 48 条热搜:
  1. 拿捏夏日高能运动穿搭        🔥 11951312
  2. 父亲的爱藏在买与不买里      🔥 11907634
  3. 假日经济活力迸发           🔥 11989625

Cookie 10 分钟内自动复用,过期后自动重新获取。

自定义中间件

其他需要特殊处理的站点(签名、Token、登录态等),写一个中间件即可:

using Aneiang.Pa.Abstractions;

public class MyAuthMiddleware : IScrapeMiddleware
{
    public int Order => 5;
    public string Name => "MyAuth";

    public async Task<ScrapeResult> InvokeAsync(ScrapeContext ctx, ScrapeDelegate next)
    {
        if (ctx.Recipe.Name == "MySite")
        {
            var token = await GetTokenAsync();
            ctx.Variables["token"] = token;
        }
        return await next(ctx);
    }

    private async Task<string> GetTokenAsync()
    {
        // 获取 token 的逻辑
        return "my-token";
    }
}

注册中间件:

Pa.Configure(c => c.UseMiddleware(new MyAuthMiddleware()));

Recipe 中用 {token} 占位:

name: MySite
category: Custom
display_name: 需要 Token 的站点
fetch:
  url: https://api.example.com/items?token={token}
  headers:
    Authorization: "Bearer {token}"
parse:
  type: html
  container: ".item"
  fields:
    title: { selector: "h3" }

中间件执行流程

请求进入

[MyAuthMiddleware] → 设置 ctx.Variables["token"]

[CacheMiddleware] → 检查缓存

[RetryMiddleware] → 失败重试

[TimeoutMiddleware] → 超时控制

[Fetch] → 实际 HTTP 请求({token} 被替换为实际值)

[Parse] → 解析响应

响应返回

IScrapeMiddleware 接口

public interface IScrapeMiddleware
{
    int Order { get; }
    string Name { get; }
    Task<ScrapeResult> InvokeAsync(ScrapeContext ctx, ScrapeDelegate next);
}
成员说明
Order执行顺序(数字越小越先执行)
Name中间件名称(用于日志)
InvokeAsync(ctx, next)处理逻辑,调用 next(ctx) 继续管道

ScrapeContext

属性说明
Recipe当前 Recipe 信息
Variables共享变量字典(中间件间传递数据)
CancellationToken取消令牌
Headers请求头
Url请求地址

未来计划

类似抖音的特殊站点(小红书、微信公众号等)未来都会有对应的内置中间件。如果你遇到了需要特殊处理的站点,欢迎在 GitHub 提 Issue 讨论。