在这篇 Node.js 用户代理设置指南中,你将了解到:
User-Agent
让我们开始吧!
为什么设置用户代理如此重要
User-Agent
例如,以下是 Chrome 在请求页面时设置的当前用户代理:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36
下面是该用户代理字符串的组成部分的详细解析:
Mozilla/5.0Windows NT 10.0; Win64; x64:Windows NT 10.0Win64x64AppleWebKit/537.36KHTML, like GeckoChrome/127.0.0.0Safari/537.36
本质上,用户代理可以揭示请求是否来自可信的浏览器或其他类型的软件。
User-Agent
什么是 Node.js 的默认用户代理?
fetch()
fetch()User-Agent
fetch()
node
httpbin.io/user-agentUser-Agent
asyncfetch()
async function getFetchDefaultUserAgent() {
// make an HTTP request to the HTTPBin endpoint
// to get the user agent
const response = await fetch("https://httpbin.io/user-agent");
// read the default user agent from the response
// and print it
const data = await response.json();
console.log(data);
}
getFetchDefaultUserAgent();
执行上面的 JavaScript 代码,你将收到如下字符串:
{ 'user-agent': 'node' }
fetch()node
反爬虫解决方案会监控传入请求中的可疑模式,例如异常的用户代理字符串。一旦检测到,这些请求将被标记为来自爬虫并被阻止。这就是为什么更改默认的 Node.js 用户代理值是避免被标记的重要措施!
如何使用 Fetch API 更改 Node.js 用户代理
User-Agent
fetch()User-Agent
本地设置用户代理
fetch()headersUser-Agent
const response = await fetch("https://httpbin.io/user-agent", {
headers: {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
},
});
将这些内容整合在一起,你将得到:
async function getFetchUserAgent() {
// make an HTTP request to HTTPBin
// with a custom user agent
const response = await fetch("https://httpbin.io/user-agent", {
headers: {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
},
});
// read the default user agent from the response
// and print it
const data = await response.json();
console.log(data);
}
getFetchUserAgent();
启动上面的脚本,这次结果将是:
{
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
}
太棒了!API 返回的用户代理与代码中配置的用户代理相匹配。现在你知道如何更改 Node.js 用户代理了。
全局设置用户代理
User-Agentfetch()
fetch()
function customFetch(url, options = {}) {
// custom headers
const customHeaders = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
...options.headers, // merge with any other headers passed in the options
};
const mergedOptions = {
...options,
headers: customHeaders,
};
return fetch(url, mergedOptions);
}
customFetch()fetch()
const response = await customFetch("https://httpbin.io/user-agent");
完整的 Node.js 脚本将是:
function customFetch(url, options = {}) {
// add a custom user agent header
const customHeaders = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
...options.headers, // merge with any other headers passed in the options
};
const mergedOptions = {
...options,
headers: customHeaders,
};
return fetch(url, mergedOptions);
}
async function getFetchUserAgent() {
// make an HTTP request to HTTPBin
// through the custom fetch wrapper
const response = await customFetch("https://httpbin.io/user-agent");
// read the default user agent from the response
// and print it
const data = await response.json();
console.log(data);
}
getFetchUserAgent();
启动上面的 Node.js 脚本,它将打印:
{
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
}
fetch()
在 Node.js 中实现用户代理轮换
User-Agent
User-Agent
在接下来的部分中,你将学习如何在 Node.js 中实现用户代理轮换!
步骤#1:获取用户代理列表
访问类似 WhatIsMyBrowser.com 的网站,并填充一些有效的用户代理值列表:
const userAgents = [
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/126.0.2592.113",
// other user agents...
];
提示:该数组包含的真实世界用户代理字符串越多,越能避免反爬虫检测。
步骤#2:随机选择一个用户代理
创建一个函数,从列表中随机选择并返回一个用户代理字符串:
function getRandomUserAgent() {
const userAgents = [
// user agents omitted for brevity...
];
// return a user agent randomly
// extracted from the list
return userAgents[Math.floor(Math.random() * userAgents.length)];
}
让我们来分解一下这个函数中发生的事情:
Math.random()userAgentsMath.floor()userAgents.length - 1
getRandomUserAgent()
步骤#3:使用随机用户代理发出 HTTP 请求
fetch()getRandomUserAgent()User-Agent
const response = await fetch("https://httpbin.io/user-agent", {
headers: {
"User-Agent": getRandomUserAgent(),
},
});
通过 Fetch API 执行的 HTTP 请求现在将具有一个随机的用户代理。
步骤#4:将所有内容整合在一起
fetch()async
以下是你的最终 Node.js 用户代理轮换脚本的样子:
function getRandomUserAgent() {
const userAgents = [
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/126.0.2592.113",
// other user agents...
];
// return a user agent randomly
// extracted from the list
return userAgents[Math.floor(Math.random() * userAgents.length)];
}
async function getFetchUserAgent() {
// make an HTTP request with a random user agent
const response = await fetch("https://httpbin.io/user-agent", {
headers: {
"User-Agent": getRandomUserAgent(),
},
});
// read the default user agent from the response
// and print it
const data = await response.json();
console.log(data);
}
getFetchUserAgent();
运行脚本 3 到 4 次。从统计学上讲,你应该会看到如下所示的不同用户代理响应:
这表明用户代理轮换功能正常。
大功告成!你现在掌握了如何在 Node.js 中使用 Fetch API 设置用户代理的技能。
结论
User-Agent
为了更强大的解决方案,可以考虑 Web Scraper API—下一代抓取服务,可以简化 Node.js 或任何其他技术中的自动化网页请求。它通过 IP 和用户代理轮换等功能有效地绕过反爬虫措施,使网页抓取比以往更加简单。
立即注册并为你的项目找到最好的产品。马上开始你的免费试用吧!