Skip to content

高级开发 - 进阶技巧

1. 等待元素出现

js
class Tool extends OPENUGC_API_V2 {
  async run() {
    // 等待元素出现
    await this.waitForSelector('.result-item');

    // 继续操作
    const items = document.querySelectorAll('.result-item');
    return items.length;
  }

  async waitForSelector(selector, timeout = 5000) {
    return new Promise((resolve, reject) => {
      const startTime = Date.now();

      function check() {
        const element = document.querySelector(selector);
        if (element) {
          resolve(element);
        } else if (Date.now() - startTime > timeout) {
          reject(new Error('Timeout waiting for ' + selector));
        } else {
          setTimeout(check, 100);
        }
      }

      check();
    });
  }
}

2. 数据抓取最佳实践

js
class Tool extends OPENUGC_API_V2 {
  async run() {
    const page = await this.OpenUrl({
      url: this.args.target_url
    });

    try {
      // 执行数据抓取逻辑
      const data = await page.execute(`
        // 等待页面加载完成
        await new Promise(resolve => setTimeout(resolve, 1000));

        const results = [];
        const items = document.querySelectorAll('.item');

        for (let item of items) {
          const title = item.querySelector('.title')?.innerText?.trim();
          const price = item.querySelector('.price')?.innerText?.trim();
          const link = item.querySelector('.title a')?.href;

          if (title && price) {
            results.push({
              title,
              price,
              link,
              timestamp: Date.now()
            });
          }
        }

        return results;
      `);

      return {
        count: data.length,
        items: data,
        extracted_at: new Date().toISOString()
      };
    } finally {
      page.close();
    }
  }
}

3. 错误处理

js
class Tool extends OPENUGC_API_V2 {
  async run() {
    const page = await this.OpenUrl({
      url: this.args.target_url,
      showLog: true  // 开启日志便于调试
    });

    try {
      const result = await page.execute(`
        try {
          // 执行主要逻辑
          const data = extractData();
          return { success: true, data };
        } catch (error) {
          return { success: false, error: error.message };
        }
      `);

      if (!result.success) {
        throw new Error(result.error);
      }

      return result.data;
    } catch (error) {
      console.error('执行失败:', error);
      return {
        error: true,
        message: error.message,
        stack: error.stack
      };
    } finally {
      page.close();
    }
  }
}

4. 循环操作

js
class Tool extends OPENUGC_API_V2 {
  async run() {
    const page = await this.OpenUrl({
      url: this.args.start_url
    });

    try {
      const allResults = [];

      for (let i = 1; i <= this.args.max_pages; i++) {
        // 翻页
        if (i > 1) {
          await page.execute(`
            const nextBtn = document.querySelector('.next-page');
            if (nextBtn && !nextBtn.disabled) {
              nextBtn.click();
              await new Promise(resolve => setTimeout(resolve, 1000));
            }
          `);
        }

        // 抓取当前页数据
        const pageData = await page.execute(`
          const items = [];
          document.querySelectorAll('.item').forEach(item => {
            items.push({
              title: item.querySelector('.title')?.innerText?.trim()
            });
          });
          return items;
        `);

        allResults.push(...pageData);

        // 避免请求过于频繁
        await this.sleep(500);
      }

      return allResults;
    } finally {
      page.close();
    }
  }
}

5. 表单自动填写

js
class Tool extends OPENUGC_API_V2 {
  async run() {
    const page = await this.OpenUrl({
      url: 'https://example.com/form'
    });

    try {
      const result = await page.execute(`
        // 填写表单
        document.querySelector('#name').value = '${this.args.name}';
        document.querySelector('#email').value = '${this.args.email}';

        // 选择下拉框
        const categorySelect = document.querySelector('#category');
        categorySelect.value = '${this.args.category}';

        // 勾选复选框
        if ('${this.args.agree}' === 'true') {
          document.querySelector('#agree').checked = true;
        }

        // 提交表单
        document.querySelector('#submit').click();

        // 等待提交结果
        await new Promise(resolve => setTimeout(resolve, 2000));

        // 获取结果
        const message = document.querySelector('.result-message').innerText;
        return message;
      `);

      return result;
    } finally {
      page.close();
    }
  }
}

相关链接

Released under the MIT License.