在互联网的世界里,数据无处不在。无论是新闻资讯、商品信息,还是社交媒体动态,这些数据都以各种形式存储在服务器上。而爬虫,就是我们获取这些数据的得力助手。今天,我们就来聊聊爬虫的基础——HTTP 请求与响应,以及如何用 Axios 和 node-fetch 这两个工具轻松上手。
一、HTTP 请求:和服务器打招呼
想象一下,你去朋友家做客,首先得敲门吧?HTTP 请求就像是你敲门的动作,告诉服务器“我来了,我想干啥”。服务器收到你的请求后,会回复你“好嘞,给你数据”或者“不行,你不能这么做”。
1.1 常见的 HTTP 请求方法
-
GET:就像你问朋友“你家有啥好吃的吗?”这是用来获取数据的。
-
POST:相当于你递给朋友一个包裹,说“这个给你,帮我存着”。这是用来提交数据的。
-
PUT/PATCH:类似于“我帮你把这个东西修一下”,用来更新数据。
-
DELETE:就像你说“这个东西不要了,扔了吧”,用来删除数据。
二、Axios 和 node-fetch:你的得力工具
在 JavaScript 世界里,发送 HTTP 请求有多种方式,但 Axios 和 node-fetch 是两个非常受欢迎的工具。它们就像你手中的万能钥匙,能轻松打开服务器的大门。
2.1 为什么选择它们?
-
Axios:它支持浏览器和 Node.js,返回的是 Promise,这样你可以很方便地处理异步操作。而且,它还支持拦截器,可以自动转换 JSON 数据,简直是懒人的福音。
-
node-fetch:轻量级,专注于 Node.js 环境,语法简洁,适合快速开发。就像一把小巧的瑞士军刀,关键时刻能派上大用场。
三、用 Axios 发送 HTTP 请求
3.1 安装 Axios
在项目中安装 Axios:
npm install axios
3.2 发送 GET 请求
const axios = require('axios');
// 发送 GET 请求
axios.get('https://api.example.com/data')
.then(response => {
console.log('服务器返回的数据:', response.data);
})
.catch(error => {
console.error('请求出错:', error);
});
就像你敲门后,朋友把好吃的递给你,response.data
就是朋友给你的“好吃的”。
3.3 发送 POST 请求
const axios = require('axios');
// 发送 POST 请求
axios.post('https://api.example.com/login', {
username: 'user123',
password: 'pass123'
})
.then(response => {
console.log('登录成功,返回数据:', response.data);
})
.catch(error => {
console.error('登录失败:', error);
});
这就像你递给朋友一个包裹,里面装着你的用户名和密码。
3.4 设置请求头
有时候,你需要告诉服务器一些额外的信息,比如你是什么类型的客户端(User-Agent),或者携带 Cookie:
const axios = require('axios');
axios.get('https://api.example.com/data', {
headers: {
'User-Agent': 'MyApp/1.0',
'Cookie': 'session=abc123'
}
})
.then(response => {
console.log('响应数据:', response.data);
})
.catch(error => {
console.error('出错:', error);
});
这就像是你敲门时,顺便告诉朋友“我是用手机来的,还带着上次的通行证”。
四、用 node-fetch 发送 HTTP 请求
4.1 安装 node-fetch
在项目中安装 node-fetch:
npm install node-fetch
4.2 发送 GET 请求
const fetch = require('node-fetch');
// 发送 GET 请求
fetch('https://api.example.com/data')
.then(response => response.json()) // 将响应体转换为 JSON
.then(data => {
console.log('服务器返回的数据:', data);
})
.catch(error => {
console.error('请求出错:', error);
});
4.3 发送 POST 请求
const fetch = require('node-fetch');
// 发送 POST 请求
fetch('https://api.example.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'user123',
password: 'pass123'
})
})
.then(response => response.json())
.then(data => {
console.log('登录成功,返回数据:', data);
})
.catch(error => {
console.error('登录失败:', error);
});
4.4 设置请求头和参数
const fetch = require('node-fetch');
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'User-Agent': 'MyApp/1.0',
'Cookie': 'session=abc123'
}
})
.then(response => response.json())
.then(data => {
console.log('响应数据:', data);
})
.catch(error => {
console.error('出错:', error);
});
五、处理 JSON 和 HTML 数据
5.1 JSON 数据
JSON 是服务器返回数据的常见格式,就像朋友给你递了一盒巧克力,Axios 和 node-fetch 都能轻松处理:
// Axios 示例
axios.get('https://api.example.com/data')
.then(response => {
console.log('JSON 数据:', response.data);
});
// node-fetch 示例
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log('JSON 数据:', data);
});
5.2 HTML 数据
如果服务器返回的是 HTML(比如网页内容),就像朋友给你递了一本菜谱,你可以用 cheerio
这样的工具来解析:
const fetch = require('node-fetch');
const cheerio = require('cheerio');
fetch('https://example.com')
.then(response => response.text()) // 获取 HTML 文本
.then(html => {
const $ = cheerio.load(html); // 加载 HTML
const title = $('title').text(); // 提取标题
console.log('网页标题:', title);
});
六、请求头与参数:让请求更专业
6.1 什么是请求头?
请求头就像是你敲门时的自我介绍。你可以告诉服务器:
-
User-Agent:我是用什么设备来的(比如浏览器类型)。
-
Cookie:我上次来的时候,你给我的通行证。
-
Content-Type:我给你递的包裹里面装的是什么类型的东西(比如 JSON、表单数据)。
6.2 如何设置请求头?
// Axios 示例
axios.get('https://api.example.com/data', {
headers: {
'User-Agent': 'MyApp/1.0',
'Cookie': 'session=abc123'
}
});
// node-fetch 示例
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'User-Agent': 'MyApp/1.0',
'Cookie': 'session=abc123'
}
});
6.3 如何设置请求参数?
有时候,你需要在 GET 请求中携带一些参数,比如搜索关键词:
// Axios 示例
axios.get('https://api.example.com/search', {
params: {
query: '爬虫',
page: 1
}
});
// node-fetch 示例
fetch('https://api.example.com/search?query=爬虫&page=1');
这就像是你敲门时说“我来查爬虫相关的资料,第一页就好”。
七、总结
通过 Axios 和 node-fetch,你可以轻松发送 HTTP 请求并处理响应数据。Axios 更适合需要复杂功能的场景,而 node-fetch 则是轻量级的选择。无论是获取 JSON 数据还是解析 HTML 页面,这些工具都能帮你在爬虫的道路上一路畅通。
如果你是初学者,建议先从 Axios 开始,它的语法更友好,功能也更强大。等你熟悉后,可以尝试 node-fetch,看看它的简洁风格是否更适合你的项目需求。