安装包和 playwright:
npm i fetchfox
npx playwright install-deps
npx playwright install
然后使用它。以下是回调风格:
import { fox } from 'fetchfox';
const workflow = await fox
.init('https://pokemondb.net/pokedex/national')
.extract({ name: 'Pokemon name', number: 'Pokemon number' })
.limit(3)
.plan();
const results = await workflow
.run(null, (delta) => { console.log(delta.item) });
for (const item of results.items) {
console.log('Item:', item);
}
如果你更喜欢,可以使用流式风格:
import { fox } from 'fetchfox';
const stream = fox
.init('https://pokemondb.net/pokedex/national')
.extract({ name: 'Pokemon name', number: 'Pokemon number' })
.stream();
for await (const delta of stream) {
console.log(delta.item);
}
你通常会想要抓取多个层级。你可以通过使用 url 字段来实现。如果你提取了 url 字段,FetchFox 将在下一步中跟随该 URL。
例如,你可以在 Pokedex 的第二页获取 HP 和攻击力:
const workflow = await fox
.init('https://pokemondb.net/pokedex/national')
.extract({
url: 'URL of pokemon profile',
name: 'Pokemon name',
number: 'Pokemon number'
})
.extract({
hp: 'Pokemon HP',
attack: 'Pokemon attack power',
})
.limit(3)
.plan();
const results = await workflow
.run(null, (delta) => { console.log(delta.item) });
for (const item of results.items) {
console.log('Item:', item);
}
这个抓取器将从 https://pokemondb.net/pokedex/national 开始,然后前往像 https://pokemondb.net/pokedex/pikachu 这样的详情页面获取 HP 和攻击力值。
你需要为你使用的 AI 提供商提供 API 密钥,例如 OpenAI。有几种方法可以做到这一点。
最简单的选项是设置 OPENAI_API_KEY 环境变量。这将由 FetchFox 库自动识别,所有 AI 调用都将通过该密钥进行。要使用此选项,请像这样运行你的代码:
OPENAI_API_KEY=sk-your-key node index.js
或者,你也可以在代码中传入你的 API 密钥,如下所示:
import { fox } from 'fetchfox';
const results = await fox
.config({ ai: ['openai:gpt-4o-mini', { apiKey: 'sk-your-key' }]})
.init('https://pokemondb.net/pokedex/national')
.extract({ name: 'Pokemon name', number: 'Pokemon number' })
.limit(3)
.run();
这将使用 OpenAI 的 gpt-4o-mini 模型以及你指定的 API 密钥。你也可以使用 OpenRouter 来访问其他提供商的 AI 模型:
const results = await fox
.config({ ai: ['openrouter:google/gemini-flash-1.5', { apiKey: 'your-openrouter-key' }]})
.init('https://pokemondb.net/pokedex/national')
.extract({ name: 'Pokemon name', number: 'Pokemon number' })
.limit(3)
.run();
选择最适合你需求的 AI 模型。
支持以下提供商
openai:...,例如 openai:gpt-4ogoogle:...,例如 google:gemini-1.5-flashopenrouter:...,例如 openrouter:anthropic/claude-3.5-haiku默认情况下,FetchFox 使用 OpenAI 的 gpt-4o-mini 模型。我们发现该模型在成本、运行时间和准确性之间提供了良好的权衡。我们有一个公共基准测试仪表板,你可以在其中查看近期提交的性能数据。