首页 / 文档 / 配置选项

配置选项

全局配置

通过 Pa.Configure() 进行全局配置:

Pa.Configure(c =>
{
    c.Options.DefaultCacheDuration = TimeSpan.FromMinutes(5);
    c.Options.DefaultTimeout = TimeSpan.FromSeconds(30);
    c.Options.RetryCount = 3;
    c.Options.EnableMetrics = true;
    c.Options.EnableTracing = true;
    c.UseRecipesFolder("./recipes");
});

选项一览

基础选项

选项默认值说明
DefaultCacheDuration5 分钟缓存有效期
DefaultTimeout30 秒HTTP 超时
RetryCount3重试次数
EnableMetricstrue是否启用指标
EnableTracingtrue是否启用追踪
EnableRateLimitfalse是否启用限流

限流选项

Pa.Configure(c => c.Options.RateLimit = new RateLimitOptions
{
    PermitLimit = 10,
    Window = TimeSpan.FromSeconds(1)
});
选项默认值说明
PermitLimit10窗口内最大请求数
Window1 秒时间窗口

熔断选项

Pa.Configure(c => c.Options.CircuitBreaker = new CircuitBreakerOptions
{
    FailureThreshold = 5,
    DurationOfBreak = TimeSpan.FromSeconds(60)
});
选项默认值说明
FailureThreshold5连续失败次数阈值
DurationOfBreak60 秒熔断持续时间

代理池配置

Pa.Configure(c => c
    .UseProxyPool(new[]
    {
        "http://127.0.0.1:7890",
        "http://127.0.0.1:7891",
    })
    .ProxyStrategy(ProxyStrategy.RoundRobin));
策略说明
ProxyStrategy.RoundRobin轮询
ProxyStrategy.Random随机

代理池自带健康跟踪,连续失败的代理会自动禁用。

加载外部 Recipe

// 从文件夹加载
Pa.Configure(c => c.UseRecipesFolder("./recipes"));

// 从单个文件加载
Pa.Configure(c => c.UseRecipeFile("./recipes/myapi.yaml"));

中间件注册

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

中间件按 Order 属性排序执行。

依赖注入集成

在 ASP.NET Core 中通过 DI 配置:

builder.Services.AddPa(opt =>
{
    opt.DefaultCacheDuration = TimeSpan.FromMinutes(10);
    opt.RecipesFolder = "./recipes";
    opt.EnableMetrics = true;
});

// 注册自定义中间件
builder.Services.AddSingleton<IScrapeMiddleware, MyAuthMiddleware>();

插件化

第三方包通过 [assembly: PaScraperModule] 自动发现:

// 在第三方程序集中
[assembly: PaScraperModule]

public class MyModule : IPaModule
{
    public void Register(IPaConfigurator config)
    {
        config.Define("MySource", b => b
            .Get("https://example.com")
            .ParseHtml(p => p
                .Container(".item")
                .Field("title", f => f.Selector("h3"))));
    }
}

引用该包后,Pa.DiscoverFromLoadedAssemblies() 会自动发现并加载。