赞
踩
import Koa from "koa" import Router from "koa-router" const app: Koa = new Koa(); const router: Router = new Router(); // 假设这里是ip请求的数据池 interface IpDataType { startTiem: number, // 第一次访问的时间 requestTimes: number, // 10分钟之内访问的次数 } let ipMap: { [key: string]: IpDataType } = {}; router.get('/testip', (ctx: Koa.Context, next) => { // 获取ip let ip: string = ctx.request.ip; let now: number = new Date().getTime(); // 判断ip有没有请求过 if (!ipMap[ip]) { ipMap[ip] = { startTiem: now, requestTimes: 1, } } else { ipMap[ip].requestTimes++; } // 判断10分钟之内有没有超过请求100次,如果有就直接屏蔽 if (now - ipMap[ip].startTiem <= 10 * 60 * 1000 && ipMap[ip].requestTimes >= 100) { ctx.body = "ip已超过请求次数" return; } // 保底逻辑,如果距离上次请求的时间超过10分钟则重置数据,以防错封 if (now - ipMap[ip].requestTimes <= 10 * 60) { ipMap[ip] = { startTiem: now, requestTimes: 1, } } ctx.body = "成功" }); app.use(router.routes()) app.listen(3000, "0.0.0.0")
// 假设这里是ip请求的数据池
interface IpDataType {
startTiem: number, // 第一次访问的时间
requestTimes: number, // 10分钟之内访问的次数
}
let ipMap: { [key: string]: IpDataType } = {};
这个是用来存储已经请求过的ip数据,用来做后续的判断
这里是简单用变量来代表ip请求数据池,一般大项目的ip请求数据池都是放在redis或者mysql中的
// 获取ip let ip: string = ctx.request.ip; let now: number = new Date().getTime(); // 判断ip有没有请求过 if (!ipMap[ip]) { ipMap[ip] = { startTiem: now, requestTimes: 1, } } else { ipMap[ip].requestTimes++; } // 判断10分钟之内有没有超过请求100次,如果有就直接屏蔽 if (now - ipMap[ip].startTiem <= 10 * 60 * 1000 && ipMap[ip].requestTimes >= 100) { ctx.body = "ip已超过请求次数" return; }
这里的反爬原理是,一定时间内,访问次数超过一定数量之后就进行禁止请求了,因为很多爬虫程序都是并发爬取的,而正常用户是达不到这么高的请求数量的,所以这个是策略之一
def requestIp():
for i in range(1000):
try:
data = requests.get("http://192.168.3.5:3000/testip");
print(data.text)
except Exception as e:
print("请求报错:" + str(e));
pass;
if __name__ == "__main__":
requestIp();
这里就是短时间内请求很多次的爬虫程序,运行过程中可以发现后面的请求都无法得到一个正常的数据了
1、请求数据加密,根据一定的规则将参数加密,然后加密字符串在放在请求头中,这样的方式能对一些初级爬虫工程师有一定作用,对于会js逆向的工程师来说是没用的
2、账号反爬,对于一些接口是要登录才能请求的,这个时候针对账号短时间内请求次数的判断是不是爬虫,这个是我用过比较好用的方式了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。