背景:最近在爬知乎,先搞一个自动登录,我是用的是可视化的webdriver来模拟登陆,因为知乎有反爬手段,使用代码输入账号密码几乎百分百出验证码,验证码是一个中文的一个英文,英文较容易,如果出了中文大不了重新登陆
此验证码是一个base64格式的图片,所以就没有采取截图的方式,直接拿到验证码的base64编码进行保存,然后识别接着输入就ok了,这么一想很容易,但是出了一个小插曲
验证码拿到以后使用base64.b64decode()后竟然是无法查看的图片也无法识别,这怎么回事
通过几个小时的摸索终于找到问题
1、发现解码失败后很奇怪,代码没问题呀,大家都这么写为什么这个不行,但是这个放到网上在线base64转图片就可以看到图,蛤这么奇怪
2、那是什么问题,我找了别人的一段base64编码的图片用我的代码,发现居然可以,代码没问题了是我的那段base64编码有问题,但是在线解码工具又可以成功……
3、此时我发现我的base64编码是一行很长就不粘了,我发现这段里面有一个‘%’字符,诶很奇怪,就去查看了网上的base64编码表发现根本没有‘%’,所以这就不是纯正的base64编码,那这是什么,想到了url编码,正好发现那段base64中频繁的出现“%0A”,一查这都是url编码中的换行符,终于发现问题了,所以就要先进行url解码再进行base64解码就可以完成总体的解码,下面粘上代码:
imgBase64 = "data:image/jpg;base64,R0lGODdhlgA8AIcAAP7+/gICAujo6BcXF9fX11ZWVmdnZyYmJsjIyJaWljY2NkdHR/Pz83d3d4iI%0AiKWlpbe3t7e3t6ioqDo6OsLCwkBAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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169auX6MmAGA27dq2b+POrXs3b90EAAAPLnw48eLGjyNPrnw58+bOn0OPLn069erWr0MPCAA7"
imgBase64 = imgBase64.split("base64,")[1]
imgBase64 = parse.unquote(imgBase64)
print(imgBase64)
if os.path.exists("Code.jpg"):
os.remove("Code.jpg")
data = base64.b64decode(imgBase64)
with open("Code.jpg", 'wb') as img:
img.write(data)
img.close()
else:
data = base64.b64decode(imgBase64)
with open("Code.jpg", 'wb') as img:
img.write(data)
img.close()
既然搞定了,哈哈知乎我来了