Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ouchengxian opened this issue Mar 2, 2022 · 5 comments
Open

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

ouchengxian opened this issue Mar 2, 2022 · 5 comments

Comments

@ouchengxian
Copy link

ouchengxian commented Mar 2, 2022

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)

@huaixu1358
Copy link

方便给一份完整代码我吗

@Ziven-L
Copy link

Ziven-L commented May 8, 2022

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

@skyformat99
Copy link

推送pr啊

@yangzhipeng1108
Copy link

yangzhipeng1108 commented Dec 8, 2022

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
Copy link

yangzhipeng1108 commented Dec 8, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants