easytrader icon indicating copy to clipboard operation
easytrader copied to clipboard

解决通用同花顺交易端输入验证码

Open ouchengxian opened this issue 2 years ago • 5 comments

env

OS: win7/ win10 / mac / linux PYTHON_VERSION: 3.x EASYTRADER_VERSION: 0.xx.xx BROKER_TYPE: gj / ht / xq / xxx

problem

how to repeat

1、通过修改 grid_strategies.py文件 2、安装Tesseract-OCR

class Xls(BaseStrategy):
‘’‘通过将 Grid 另存为 xls #文件再读取的方式获取 grid 内容’‘’ def init(self, tmp_folder: Optional[str] = None):
‘’‘param tmp_folder: 用于保持临时文件的文件夹’‘’ super().init() self.tmp_folder = tmp_folder def get(self, control_id: int) -> List[Dict]: logger.info("保存 grid 内容为 xls 文件模式") grid = self._get_grid(control_id)
# ctrl+s 保存 grid 内容为 xls 文件 self._set_foreground(grid) # setFocus buggy, instead of SetForegroundWindow grid.type_keys("^s", set_foreground=False) ################################ #检查是否需要输入验证码 if (self._trader.app.top_window().window( class_name="Static", title_re="验证码" ).exists(timeout=1)): #检查是否有验证码输入Window file_path = "tmp.png" count = 5 found = False while count > 0: self._trader.app.top_window().window( control_id=0x965, class_name="Static" ).capture_as_image().save( file_path ) # 保存验证码图片 captcha_num = captcha_recognize(file_path).strip() # 识别验证码 captcha_num = "".join(captcha_num.split()) logger.info("captcha result-->" + captcha_num) if len(captcha_num) == 4: ###### 模拟输入验证码##### editor = self._trader.app.top_window().window( control_id=0x964, class_name="Edit" ) editor.select() editor.type_keys(captcha_num) ######################### self._trader.app.top_window().set_focus() pywinauto.keyboard.SendKeys("{ENTER}") # 模拟发送enter,点击确定 if self._trader.app.window(title='另存为').exists(timeout=1): found = True break logger.info(f"captcha result:{captcha_num} error") count -= 1 self._trader.wait(0.1) self._trader.app.top_window().window( control_id=0x965, class_name="Static" ).click() if not found: self._trader.app.top_window().Button2.click() # 点击取消 #上述是验证码处理 ##################################
temp_path = tempfile.mktemp(suffix=".xls", dir=self.tmp_folder)
self._set_foreground(self._trader.app.top_window()) # alt+s保存,alt+y替换已存在的文件 self._trader.app.top_window().Edit1.set_edit_text(temp_path) self._trader.wait(0.1) self._trader.app.top_window().type_keys("%{s}%{y}", set_foreground=False) # Wait until file save complete otherwise pandas can not find file self._trader.wait(0.2) if self._trader.is_exist_pop_dialog(): self._trader.app.top_window().Button2.click() self._trader.wait(0.2)
return self._format_grid_data(temp_path)

ouchengxian avatar Mar 02 '22 12:03 ouchengxian

方便给一份完整代码我吗

huaixu1358 avatar Mar 10 '22 06:03 huaixu1358

您好,可以给我一份完整代码吗?

Ziven-L avatar May 08 '22 13:05 Ziven-L

推送pr啊

skyformat99 avatar Oct 13 '22 02:10 skyformat99

class Xls(BaseStrategy): """ 通过将 Grid 另存为 xls 文件再读取的方式获取 grid 内容 """

def __init__(self, tmp_folder: Optional[str] = None):
    """
    :param tmp_folder: 用于保持临时文件的文件夹
    """
    super().__init__()
    self.tmp_folder = tmp_folder

def get(self, control_id: int) -> List[Dict]:
    grid = self._get_grid(control_id)

    # ctrl+s 保存 grid 内容为 xls 文件
    self._set_foreground(grid)  # setFocus buggy, instead of SetForegroundWindow
    grid.type_keys("^s", set_foreground=False)
    # count = 10
    # while count > 0:
    #     if self._trader.is_exist_pop_dialog():
    #         break
    #     self._trader.wait(0.2)
    #     count -= 1

    if  (self._trader.app.top_window().window(class_name="Static", title_re="验证码").exists(timeout=1)): #检查是否有验证码输入Window
        file_path = "tmp.png"
        count = 5
        found = False
        while count > 0:
            self._trader.app.top_window().window(
                control_id=0x965, class_name="Static"
            ).capture_as_image().save(
                file_path
            )  # 保存验证码

            captcha_num = captcha_recognize(file_path).strip()  # 识别验证码
            captcha_num = "".join(captcha_num.split())
            logger.info("captcha result-->" + captcha_num)
            if len(captcha_num) == 4:

                editor = self._trader.app.top_window().window(
                    control_id=0x964, class_name="Edit")
                editor.select()
                editor.type_keys(captcha_num)

                self._trader.app.top_window().set_focus()
                pywinauto.keyboard.SendKeys("{ENTER}")  # 模拟发送enter,点击确定
                if self._trader.app.window(title='另存为').exists(timeout=1):
                    found = True
                    break
                logger.info(f"captcha result:{captcha_num} error")
            count -= 1
            self._trader.wait(0.1)
            self._trader.app.top_window().window(
                control_id=0x965, class_name="Static"
            ).click()
        if not found:
            self._trader.app.top_window().Button2.click()  # 点击取消

    temp_path = tempfile.mktemp(suffix=".xls", dir=self.tmp_folder)
    self._set_foreground(self._trader.app.top_window())

    # alt+s保存,alt+y替换已存在的文件
    self._trader.app.top_window().Edit1.set_edit_text(temp_path)
    self._trader.wait(0.1)
    self._trader.app.top_window().type_keys("%{s}%{y}", set_foreground=False)
    # Wait until file save complete otherwise pandas can not find file
    self._trader.wait(0.2)
    if self._trader.is_exist_pop_dialog():
        self._trader.app.top_window().Button2.click()
        self._trader.wait(0.2)

    return self._format_grid_data(temp_path)

def _format_grid_data(self, data: str) -> List[Dict]:
    with open(data, encoding="gbk", errors="replace") as f:
        content = f.read()

    df = pd.read_csv(
        StringIO(content),
        delimiter="\t",
        dtype=self._trader.config.GRID_DTYPE,
        na_filter=False,
    )
    return df.to_dict("records")

yangzhipeng1108 avatar Dec 08 '22 09:12 yangzhipeng1108

Tesseract 使用参考这两文章https://blog.csdn.net/u010454030/article/details/80515501 和 https://blog.csdn.net/wang_hugh/article/details/80760940

yangzhipeng1108 avatar Dec 08 '22 09:12 yangzhipeng1108