Profiles
Profiles 允许你在多个会话之间持久化用户数据——例如存储、cookies、缓存和登录状态。这使得自动化更加顺畅、身份验证更加简化,并优化了性能。
核心优势
- 复用浏览历史:用户可以在多个会话之间复用其浏览历史。
- 保持登录状态:在某些站点上保持登录状态,减少重复身份验证的需要。
- 提升页面加载速度:增强网页的加载速度。
- 降低被机器人检测的风险:降低被识别为机器人的几率。
使用 Profiles
1. 创建 Profile
首先,使用 Profiles API 创建一个新的 profile。请记下返回的 profileId;你将使用它把该 profile 分配给一个新会话。
import { ScrapelessClient } from '@scrapeless-ai/sdk';
const client = new ScrapelessClient({ apiKey: 'API Key' });
const createResponse = await client.profiles.create('My Profile');
console.log('Profile created:', createResponse);2. 使用 Profile
创建 profile 之后,你可以将其添加到新会话中以复用其数据。通过在会话配置中包含 profileId 来分配该 profile。
import { ScrapelessClient } from '@scrapeless-ai/sdk';
const client = new ScrapelessClient({ apiKey: 'API Key' });
const { browserWSEndpoint } = client.browser.create({
sessionName: 'My Browser',
sessionTTL: 30000,
profileId: 'your-profile-id',
});
(async () => {
const browser = await puppeteer.connect({browserWSEndpoint});
const page = await browser.newPage();
await page.goto('https://www.scrapeless.com');
console.log(await page.title());
await browser.close();
})();如果你希望新会话更新 profile 数据,则必须在 profile 对象中设置 profilePersist: true。应在会话中首次使用某个新 profile 时进行此设置,以确保其数据能够被保存以供后续使用。
const { browserWSEndpoint } = client.browser.create({
sessionName: 'My Browser',
sessionTTL: 30000,
profileId: 'your-profile-id',
profilePersist: true,
});默认情况下,context 会加载上一个会话保存的数据,但不会对其进行更新。如果你需要存储新的 cookies、身份验证令牌或缓存数据,则必须在创建会话时设置 profilePersist: true。数据将在会话关闭时被保存。这可以确保会话期间所做的任何更改——例如登录、保存站点偏好或缓存资源——都能被保留下来供未来的会话使用,而不会在会话结束时丢失。
3. 检索 Profiles
你可以通过 ID 获取特定的 profile,或使用查询参数列出你已创建的所有 profiles。完整的 schema 和参数请参阅 Profile API reference。
// get a specific profile
const profile = await client.profiles.get('your-profile-id');
// get profile list
const profiles = await client.profiles.list({ page: 1, pageSize: 10 });当启用 profilePersist: true 时,仅会保存最后关闭的那个会话的数据。
4. 在多个会话之间共享 Profile
如果你希望多个会话共享同一个 profile,默认设置 profilePersist: false 允许你在多个会话之间使用先前的 profile 配置而不做任何更改。如果你希望在这些会话中更新 profile,则需要启用持久化。
const { browserWSEndpoint } = client.browser.create({
sessionName: 'My Browser',
sessionTTL: 30000,
profileId: 'your-profile-id',
});注意:当启用 profilePersist: true 时,仅会保存最后关闭的那个会话的数据。
5. 删除 Profiles
删除未使用的 profiles 以释放资源。一旦删除,该 profile 将无法再被附加到任何会话。
const deleteResponse = await client.profiles.delete('your-profile-id');👉 有关 profiles 的示例和代码样例,请访问 Product Updates | New Profile Feature。