写在前面
- 之前写网络爬虫程序时发现,大部分的爬取地址的参数都是有规律的数字;
- 通过这个发现,其实可以基于这个数字做加密,以此来反爬取;
- hashids有多语言的实现,这里讲的是基于python语言;
- 据了解,Youtube网站就是这么做的。
hashids介绍
- hashids库安装:
pip install hashids
- 如下,Hashids类的构造参数中salt其实是设置的私钥,通过这个私钥,将数字转换成一串看上去无规则的字符串,解码后是一个元组的形式;
>>> import hashids >>> hashandle = hashids.Hashids(salt="secretkey") >>> hashandle.encode(123456) 'E57VB' >>> hashandle.decode("E57VB") (123456,)
- 另外,encode方法的传参还可以是多个数字,同样可以做加密和解密;
>>> hashandle.encode(12,34,56,78) 'k6u8hN3IwV' >>> hashandle.decode("k6u8hN3IwV") (12, 34, 56, 78) >>>
- 如下是hashids这个库源码中的构造器部分,还可以设置生成字符串的最小长度,对应的映射数据