got 使用代理爬虫模拟登录获取数据
用到的包tough-cookie 自动存放cookie got 请求库 hpagent 隧道代理
注意事项
- ⚠️got这个包是原生ESM,不再提供 CommonJS 导出 解决办法降级到v11版本
创建got实例
const { CookieJar } = require('tough-cookie');
const got = require('got')
const { v4 } = require('uuid')
const { HttpsProxyAgent } = require('hpagent');
// 创建got实例
const jar= new CookieJar(null,{rejectPublicSuffixes:false})
const request = got.extend({
// 传递CookieJar实例
cookieJar: jar,
// 设置请求重试次数
retry:0,
// 设置请求超时时间
timeout:4000,
// 忽略cookie错误
ignoreInvalidCookies: true,
// 设置请求头
headers: {
'User-Agent': `Dalvik/2.1.0 (Linux; U; Android ${Math.floor(Math.random() * (9 - 12 + 1) + 9)}; MI${Math.floor(Math.random() * (10 - 12 + 1) + 10)} Build/SKQ1.210216.001) (device:MI${Math.floor(Math.random() * (10 - 12 + 1) + 10)}) Language/zh_CN xxx.xxx.xxx/ChaoXingStudy_3_5.1.4_android_phone_614_74 (@Kalimdor)_${v4(16)}`,
'X-Requested-With': 'com.chaoxing.mobile'
}
})
设置 agent
这里我们使用 got推荐的hpagent
- 流行的
tunnel包是无人维护的。使用风险自负。 - 该
proxy-agent系列不遵循最新的 Node.js 功能并且缺乏支持。
我们接着补充上面代码
{
agent: {
https: new HttpsProxyAgent({
keepAlive: true,
keepAliveMsecs: 1000,
maxSockets: 256,
maxFreeSockets: 256,
proxy: `http:${host}:${port}`,
})
}
}
对应用法
| 类型 | 代理 | 服务器 |
|---|---|---|
HttpProxyAgent | HTTP | HTTP |
HttpProxyAgent | HTTPS | HTTP |
HttpsProxyAgent | HTTP | HTTPS |
HttpsProxyAgent | HTTPS | HTTPS |
测试
这里就不贴具体代码
// 模拟登录
await request.post('xxxxx',{form})
// 获取数据
await request.get('xxxx')
完整代码
const { CookieJar } = require('tough-cookie');
const got = require('got')
const { v4 } = require('uuid')
const { HttpsProxyAgent } = require('hpagent');
// 创建got实例
const jar= new CookieJar(null,{rejectPublicSuffixes:false})
const request = got.extend({
// 传递CookieJar实例
cookieJar: jar,
// 设置请求重试次数
retry:0,
// 设置请求超时时间
timeout:4000,
// 忽略cookie错误
ignoreInvalidCookies: true,
// 设置请求头
headers: {
User-Agent': `Dalvik/2.1.0 (Linux; U; Android ${Math.floor(Math.random() * (9 - 12 + 1) + 9)}; MI${Math.floor(Math.random() * (10 - 12 + 1) + 10)} Build/SKQ1.210216.001) (device:MI${Math.floor(Math.random() * (10 - 12 + 1) + 10)}) Language/zh_CN xxx.xxx.xxx/ChaoXingStudy_3_5.1.4_android_phone_614_74 (@Kalimdor)_${v4(16)}`,
'X-Requested-With': 'com.chaoxing.mobile'
}
})
// 模拟登录
await request.post('xxxxx',{form})
// 获取数据
await request.get('xxxx')