CAPSOLVER
博客
如何使用 Axios 进行网页抓取

如何使用 Axios 进行网页抓取

Logo of CapSolver

Adélia Cruz

Neural Network Developer

23-Sep-2024

Axios 是什么?

Axios 是一个流行的 JavaScript 库,用于在浏览器和 Node.js 中发出 HTTP 请求。它简化了异步 HTTP 请求的发出,并允许您使用 Promise 轻松处理响应。

特性:

  • 基于 Promise: 使用 JavaScript Promise,使异步操作更易于管理。
  • 浏览器和 Node.js 支持: 在两种环境中都能无缝工作。
  • 自动 JSON 解析: 自动解析 JSON 响应。
  • 拦截器: 支持请求和响应拦截器,用于全局管理请求和处理响应。
  • 错误处理: 提供内置机制来处理错误。

先决条件

在使用 Axios 之前,请确保您已安装:

  • Node.js 用于服务器端使用。
  • npmyarn 用于安装软件包。

安装

您可以使用 npm 或 yarn 安装 Axios:

bash 复制代码
npm install axios

bash 复制代码
yarn add axios

基本示例:发出 GET 请求

以下是如何使用 Axios 执行简单的 GET 请求:

javascript 复制代码
const axios = require('axios');

axios.get('https://httpbin.org/get')
  .then(response => {
    console.log('状态码:', response.status);
    console.log('响应主体:', response.data);
  })
  .catch(error => {
    console.error('错误:', error);
  });

网络抓取示例:从 API 获取 JSON 数据

让我们从 API 获取数据并打印结果:

javascript 复制代码
const axios = require('axios');

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => {
    const posts = response.data;
    posts.forEach(post => {
      console.log(`${post.title} — ${post.body}`);
    });
  })
  .catch(error => {
    console.error('错误:', error);
  });

使用 CapSolver 和 Axios 处理验证码

在本节中,我们将把 CapSolver 与 Axios 集成以绕过验证码。CapSolver 提供了一个 API 用于解决 ReCaptcha V3 和 captcha 等验证码。

我们将演示如何使用 CapSolver 解决 ReCaptcha V3 并在请求中使用解决方案。

示例:使用 CapSolver 和 Axios 解决 ReCaptcha V3

首先,安装 Axios 和 CapSolver:

bash 复制代码
npm install axios
npm install capsolver

现在,以下是如何解决 ReCaptcha V3 并在您的请求中使用解决方案:

javascript 复制代码
const axios = require('axios');
const CAPSOLVER_KEY = 'YourKey';
const PAGE_URL = 'https://antcpt.com/score_detector';
const PAGE_KEY = '6LcR_okUAAAAAPYrPe-HK_0RULO1aZM15ENyM-Mf';
const PAGE_ACTION = 'homepage';

async function createTask(url, key, pageAction) {
  try {
    const apiUrl = 'https://api.capsolver.com/createTask';
    const payload = {
      clientKey: CAPSOLVER_KEY,
      task: {
        type: 'ReCaptchaV3TaskProxyLess',
        websiteURL: url,
        websiteKey: key,
        pageAction: pageAction
      }
    };
    const headers = {
      'Content-Type': 'application/json',
    };
    const response = await axios.post(apiUrl, payload, { headers });
    return response.data.taskId;

  } catch (error) {
    console.error('创建 CAPTCHA 任务时出错:', error);
    throw error;
  }
}

async function getTaskResult(taskId) {
  try {
    const apiUrl = 'https://api.capsolver.com/getTaskResult';
    const payload = {
      clientKey: CAPSOLVER_KEY,
      taskId: taskId,
    };
    const headers = {
      'Content-Type': 'application/json',
    };
    let result;
    do {
      const response = await axios.post(apiUrl, payload, { headers });
      result = response.data;
      if (result.status === 'ready') {
        return result.solution;
      }
      await new Promise(resolve => setTimeout(resolve, 5000)); // 等待 5 秒后重试
    } while (true);

  } catch (error) {
    console.error('获取 CAPTCHA 结果时出错:', error);
    throw error;
  }
}

function setSessionHeaders() {
  return {
    'cache-control': 'max-age=0',
    'sec-ch-ua': '"Not/A)Brand";v="99", "Google Chrome";v="107", "Chromium";v="107"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': 'Windows',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-user': '?1',
    'sec-fetch-dest': 'document',
    'accept-encoding': 'gzip, deflate',
    'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,en-US;q=0.7',
  };
}

async function main() {
  const headers = setSessionHeaders();
  console.log('正在创建 CAPTCHA 任务...');
  const taskId = await createTask(PAGE_URL, PAGE_KEY, PAGE_ACTION);
  console.log(`任务 ID:${taskId}`);

  console.log('正在检索 CAPTCHA 结果...');
  const solution = await getTaskResult(taskId);
  const token = solution.gRecaptchaResponse;
  console.log(`令牌解决方案:${token}`);

  const res = await axios.post('https://antcpt.com/score_detector/verify.php', { 'g-recaptcha-response': token }, { headers });
  const response = res.data;
  console.log(`得分:${response.score}`);
}

main().catch(err => {
  console.error(err);
});

使用 Axios 处理代理

要将您的请求通过 Axios 中的代理路由:

javascript 复制代码
const axios = require('axios');

axios.get('https://httpbin.org/ip', {
  proxy: {
    host: 'proxyserver',
    port: 8080,
    auth: {
      username: 'username',
      password: 'password'
    }
  }
})
  .then(response => {
    console.log('响应主体:', response.data);
  })
  .catch(error => {
    console.error('错误:', error);
  });

您可以使用 withCredentials 选项在 Axios 中处理 Cookie:

javascript 复制代码
const axios = require('axios');

axios.get('https://httpbin.org/cookies/set?name=value', { withCredentials: true })
  .then(response => {
    console.log('Cookie:', response.headers['set-cookie']);
  })
  .catch(error => {
    console.error('错误:', error);
  });

高级用法:自定义标头和 POST 请求

您可以使用 Axios 发送自定义标头并执行 POST 请求:

javascript 复制代码
const axios = require('axios');

const headers = {
  'User-Agent': 'Mozilla/5.0 (compatible)',
  'Accept-Language': 'en-US,en;q=0.5',
};

const data = {
  username: 'testuser',
  password: 'testpass',
};

axios.post('https://httpbin.org/post', data, { headers })
  .then(response => {
    console.log('响应 JSON:', response.data);
  })
  .catch(error => {
    console.error('错误:', error);
  });

结论

使用 Axios,您可以轻松地在 Node.js 和浏览器环境中管理 HTTP 请求。通过将其与 CapSolver 集成,您可以绕过 ReCaptcha V3 和 captcha 等验证码,从而访问受限内容。

合规声明: 本博客提供的信息仅供参考。CapSolver 致力于遵守所有适用的法律和法规。严禁以非法、欺诈或滥用活动使用 CapSolver 网络,任何此类行为将受到调查。我们的验证码解决方案在确保 100% 合规的同时,帮助解决公共数据爬取过程中的验证码难题。我们鼓励负责任地使用我们的服务。如需更多信息,请访问我们的服务条款和隐私政策。

更多