获取市面上普遍使用的 UA

184 阅读1分钟

预计时间 2:00 字数 420 语言 ZH

您的 puppeteer 程序如果要随机选取目前市面上普遍使用的 UA ,应该从何处采集这么多的 UA 呢?好在已经有人发布了相关的库 user-agents,此库生成的 UA 包含信息如下:

{
  "appName": "Netscape",
  "connection": {
    "downlink": 10,
    "effectiveType": "4g",
    "rtt": 0
  },
  "platform": "Win32",
  "pluginsLength": 3,
  "vendor": "Google Inc.",
  "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
  "viewportHeight": 660,
  "viewportWidth": 1260,
  "deviceCategory": "desktop",
  "screenHeight": 800,
  "screenWidth": 1280
}

不仅包含 ua,还有窗口尺寸、视口尺寸,正好满足我需要随机 UA 和随机窗口尺寸的需求。当然,我们也不能设置一些很离谱的尺寸,而且还要限制浏览器类型、操作系统等,下面是随机生成包含限制条件的 UA 示例:

const userAgents = require("user-agents");
var useragent = require("useragent");

const ua = new userAgents((data) => {
  const a = useragent.parse(data.userAgent);

  return (
    data.deviceCategory === "desktop" &&
    data.weight > 0.0006 &&
    a.family === "Chrome" &&
    ["Windows", "Mac OS X"].includes(a.os.family) &&
    data.viewportWidth >= 1200 &&
    data.viewportHeight > 740
  );
});

const ua1 = ua.random();

console.log(ua1.data);

在此示例中限制生成 ua 的操作为 windows 和 Mac OS ,浏览器类型为 Chrome,并且对视口尺寸做了一定限制。

相关阅读

Puppeteer + opencv.js 自动化脚本实践经验总结(part 1)

Puppeteer + opencv.js 自动化脚本实践经验总结(part 2)

Puppeteer 常用连接配置

另外,这是我发布在 bilibili 上的相关视频 手把手带您实操 puppeteer,如果您是 puppeteer 的新手,这个系列视频将很适合您。