詞達人模擬點擊完成答題代碼開源(基本都可以自動)

本方法採用ocr文字識別獲取座標,然後與答案進行對比,點擊屏幕

在這裏插入圖片描述

1.申請某度api

具體方法參考我之前的博客

2.fiddler配置參考我這個博客

3.可以去下方鏈接看效果

https://www.bilibili.com/video/BV1AQ4y1T7qx/

詞達人利用python自動答題

4.對代碼的解析(拒絕白嫖,從我做起)

## 2020.04.16
## jun_軍
## qq:604803231
## blog主頁:https://blog.csdn.net/weixin_44868057
## qq交流羣:635032789 (進羣密碼:詞達人)
##方便小白觀看,我沒有定義函數

from aip import AipOcr
import json
import pyautogui
import numpy as np
import cv2 as cv
import time
import os

try:

    while True:


        ##1截圖以及圖片處理

        img = pyautogui.screenshot(region=[0,0,592,1040]) # x,y,w,h
        img.save('1/answer.jpg')



        ## 2圖片灰度處理
        def access_pixels(image):
            height, width, channels = image.shape
            print("width:%s,height:%s,channels:%s" % (width, height, channels))

            for row in range(height):
                for list in range(width):
                    for c in range(channels):
                        pv = image[row, list, c]
                        image[row, list, c] = 255 - pv
            # cv.imshow("AfterDeal", image)


        src = cv.imread('1/answer.jpg')
            # cv.imshow('OriginalImage', src)

            # 獲取當前系統以運行的週期數
        t1 = cv.getTickCount()
            # 運行函數
        access_pixels(src)
            # 再次獲取當前系統以運行的週期數
        t2 = cv.getTickCount()
            # 計時週期數差值除以每秒週期數,獲得處理時間
        print("time cost:%s s" % ((t2 - t1) / cv.getTickFrequency()))
        cv.imwrite('2/answer.jpg',src)

        ## 3圖片放大10倍
            # 已知數據集位置
        indir = "2/"

            # 保存的數據集位置
        outdir = "3/"

        cout = 0
        for fileName in os.listdir(indir):
            if fileName == '.DS_Store':
                continue
            cout = cout + 1
            # print(cout)
            # print(fileName)
            img_dir = os.path.join(indir, fileName)  # 獲取圖片的名字
            # print(img_dir)
            src = cv.imread(img_dir)  # 讀取圖片
            h1, w1 = src.shape[:2]
            # print(h1, w1)  # 打印長和寬
            r = 1 / 10 # 縮小倍數
            # 進行縮放
            dst = cv.resize(src, (int(w1 / r), int(h1 / r)), interpolation=cv.INTER_CUBIC)  # 使用雙立方插值
            h2, w2 = dst.shape[:2]
            # print(h2, w2)  # 打印長和寬
            # print(outdir + fileName)
            cv.imwrite(outdir + fileName, dst)


            ## 4圖片顯示增強
            I = cv.imread('3/answer.jpg', flags=0)
            aa = 2
            Oa = I * float(aa)
            Oa[Oa > 255] = 255
            Oa = np.round(Oa)
            Oa = Oa.astype(np.uint8)
            cv.imwrite('4/answer.jpg', Oa)






        ##5.解析本地json文件答案
        type = 0
        lodec = 'responseBody.txt'
        # def getAnswer():
        #     print('搜尋答案....')

                              #hhh=[]
        answers = []
        data = json.loads(open(lodec, "r", encoding='utf-8').read())
        # 多選
        if data['data']['topic_mode'] in [31]:
            options = data['data']['options']
            for option in options:
                if option['answer'] == True:
                    answers.append(option['content'].replace('adj','').replace('adv','').replace('noun','').replace(';','').replace(',','').replace('verb',''))
        # 單選
        if data['data']['topic_mode'] in [11, 22, 42]:
            options = data['data']['options']
            for option in options:
                if option['answer'] == True:
                    answers.append(
                        option['content'].replace(' ', '').replace(';', ';').replace(',', ',').replace('.', '').replace('…',
                               '').replace('adj','').replace('adv','').replace('noun','').replace('verb','').replace(';','').replace(',','').replace('寫',''))
        # 選詞
        if data['data']['topic_mode'] in [32]:
            options = data['data']['answer_content']['answer_arr']
            for option in options:
                # print(option)
                answers.append(option.replace('\'','').replace('j','').replace('l','').replace('J',''))


        # 填空
        if data['data']['topic_mode'] in [51]:
            type = 1
            answers.append(data['data']['answer_content'])
        for a in answers:
            print(a)


            # return answers



        print("答案:",answers)


        ##6.ocr識別



        """ 你的 APPID AK SK  圖2的內容"""
        APP_ID = '*********'
        API_KEY = '************************'
        SECRET_KEY = '************************'


        client = AipOcr(APP_ID, API_KEY, SECRET_KEY)


        fname = './4/answer.jpg'
        # fname = 'screenshot.png'
        # """ 讀取圖片 """
        def get_file_content(filePath):
            with open(filePath, 'rb') as fp:
                return fp.read()
        #
        image = get_file_content(fname)

        """ 調用通用文字識別, 圖片參數爲本地圖片 """
        client.general(image)

        # options = {}
        # options["recognize_granularity"] = "big"
        # options["language_type"] = "CHN_ENG"
        # options["detect_direction"] = "true"
        # options["detect_language"] = "true"
        # options["vertexes_location"] = "true"
        # options["probability"] = "true"


        results = client.general(image)["words_result"] # 還可以使用身份證駕駛證模板,直接得到字典對應所需字段


        h = []
        t = []
        for result in results:
            text = result["words"].replace(' ','').replace('adj','').replace('adv','').replace('I','').replace('gan√','gain').replace("I","").replace('j','').replace('J','').replace('i','')\
                .replace('noun','').replace('verb','').replace('ver','').replace('ad','').replace(';','').replace(',','').replace('寫','')
            b= (result["location"]['left']/int('10')+int('10'),result["location"]['top']/int('10')+int('10'))
            h.append(text)
            t.append(b)


            # e = (text)
            # text = print(result["words"].replace(';', '')) # 只有中文英文
            #
            # # f = print(a.replace('None',''))     #
            # location = result["location"]
            # # a= [result["location"]['left'],result["location"]['top']]
            # c= list(text)+list(b)
            # text1=list(text)+list(b)
            #
            # # # print(re.findall(r"\d+\.?\d*",text))
            # # content = list("".join(a)) + list(b)
            # t=[]

        # print('識別到的座標:',t)
        print("識別的:",h)

        if len(answers)>200:

            break
        #
        # if  len(list(h)) <100:
        # tmp = [val for val in h if val in answers]  # 列表推導式求的兩個列表的交集

        #     pass
        ## 已知的答案與識別到的進行對比,然後將座標賦值給我們要的答案
        else:
            i=0
            q=0
            zuobiao =[]
            while i < len(answers):
                p= h.index(answers[i])
                zuobiao = list(t[p])
                # i +=1
                # print(zuobiao)

                x=int(zuobiao[0])

                y=(zuobiao[1])
                # print(x)
                # print(y)

                # PyMouse.click(x,y)
                # pyautogui.moveTo(x, y, duration=1)
                pyautogui.click(x, y)
                i += 1
                time.sleep(1)

            time.sleep(1)
            k = 0
            while k<2:
                pyautogui.click(523, 1000)
                k +=1
                # time.sleep(1)

            time.sleep(3)
except:
    print("情況1:仔細看我的博客,和前面的1-4點內容創建文件夾,\n情況2::當前的頁面不在答題界面 \n情況3:如果出現不能自動答題,一定要聯繫羣主")


我已經程序打包,如若需要可前往下載,感謝支持
鏈接:https://pan.baidu.com/s/1ZTbo9-aJuM887YfzqLtKXw
提取碼:3el3

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章