前一段答题特别火的时候写了一个微信头脑王者的小脚本来辅助答题,原理是将问题百度,然后看选项在搜索结果中出现的频率判断正确答案,准确率虽然不能达到百分之百,但是最起码能提高不少答题正确率。


首先导入需要使用的包(具体每个包是干啥的可以自行百度,这样记忆效果也比较好):

# -*- coding: utf-8 -*-
import os
import random
import requests
import subprocess

from PIL import Image
from aip import AipOcr
from io import BytesIO


然后是配置文件(就是在屏幕中问题出现的区域和答案出现的区域,point就是点击的位置):


config = {
'head_king': {
'title': (80, 500, 1000, 880),
'answers': (80, 960, 1000, 1720),
'point': [
(316, 993, 723, 1078),
(316, 1174, 723, 1292),
(316, 1366, 723, 1469),
(316, 1570, 723, 1657),
]
}
}

获取屏幕截图函数,当出现问题和答案后,进行截图:
def get_screen_img():
"""获取屏幕截图"""
phone_img = subprocess.Popen('adb shell screencap -p', shell=True, stdout=subprocess.PIPE)
screen_img = phone_img.stdout.read()
# 格式化到windows
screen_img = screen_img.replace(b'\r\r\n', b'\n')

img_fb = BytesIO()
img_fb.write(screen_img)

img = Image.open(img_fb)
question_title_img = img.crop(config['head_king']['title'])
question_answers_img = img.crop(config['head_king']['answers'])

new_img = Image.new('RGBA', (920, 1140))
new_img.paste(question_title_img, (0, 0, 920, 380))
new_img.paste(question_answers_img, (0, 380, 920, 1140))

new_img_fb = BytesIO()
new_img.save(new_img_fb, 'png')
return new_img_fb

这个函数的作用是将图片中的文字提取出来(使用的是百度的文字识别,是免费的,没有的可以去注册个,新新建个应用就可以了,APP_ID,API_KEY,SECRET_KEY这三项在注册后会生成自己的):
def get_img_word(img):
APP_ID = '**********'
API_KEY = '******************'
SECRET_KEY = '****************************'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
res = client.basicGeneral(img)
return res


然后就是讲图片内的问题进行百度啦(计算网页内几个选项出现的次数):
def use_baidu_search(question, answers):
url = 'https://www.baidu.com/s'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0'
}
data = {
'wd': question
}
res = requests.get(url, params=data, headers=headers)
res.encoding = 'utf-8'
html = res.text

for i in range(len(answers)):
answers[i] = (html.count(answers[i]), answers[i], i)
answers.sort(reverse=True)

return answers


click函数,作用是自动点击屏幕,也可以不使用此函数,自己分析后手动点击:
def click(point):
cmd = 'adb shell input swipe %s %s %s %s %s' % (
point[0],
point[1],
point[0] + random.randint(0, 3),
point[1] + random.randint(0, 3),
200
)