Table of Contents
Automated collection tasks based on pywinauto
Implementation technology
Code
Home Backend Development Python Tutorial Steps and methods to implement automated collection tasks using Python and pywinauto

Steps and methods to implement automated collection tasks using Python and pywinauto

Apr 26, 2023 pm 11:13 PM
python pywinauto

Automated collection tasks based on pywinauto

Implementation technology

This program uses a Python automation library----pywinauto, because the official version has not been updated for a long time, so the python version The highest can only be around Python 3.7, I use Python 3.7.1. I used it to simulate entering words, copying example sentences, getting example sentences, clearing the clipboard, and then repeating this operation. Overall, the implementation is relatively crude. Moreover, in order Simple, I manually switch to the example sentence page, so I don’t have to use a program to switch to the example sentence page.

Code

requirements.txt

pyperclip==1.8.2
pywin32==304
pywinauto==0.6.8
Copy after login

Code

import os
import random
import time
import re
from typing import Dict, List
from pywinauto.application import Application
from pywinauto import mouse
from pywinauto import keyboard
import pyperclip
import json


# 程序处理中的各种路径
dir_path = r"C:/Users/Dick/Desktop/work/DragonEnglish/tools"
input_path = os.path.join(dir_path, r"input.txt")
output_path = os.path.join(dir_path, r"output.json")
error_path = os.path.join(dir_path, r"error.txt")
# 顺序错误的单词
error_words = []
# 有道词典的进程id
processId = 13840


def line_process(content: str) -> str:
    """
    去除所有空行, 再去除前面四行无关内容
    """
    lines = content.split("\r\n")
    # 因为例句开头是 数字. 开头的, 所以先以这个为特点来进行过滤掉多复制的开头
    count = 0
    for i in range(len(lines)):
        if re.match(r"\d+\.", lines[i]):
            count = i
            break

    lines = lines[count:]
    filter_lines = []
    for line in lines:
        if line.strip() != "":  # 过滤空行
            if not line.startswith("youdao") and not \
                    (line.startswith("《") and line.endswith("》")):  # 过滤来源
                filter_lines.append(line)

    if len(filter_lines) % 3 != 0:
        raise Exception("抓取数据错误")

    content = "\n".join(filter_lines) + "\n"  # 补上一个 \n, 不然正则会漏掉一个结果
    return content


def to_list(line: str) -> List[Dict[str, str]]:
    """
    直接生成列表字典对象
    [{
        "no": 1,
        "original": "",
        "translate"
    }]
    """
    sentences = []
    # 正则表达式
    REGEXP = r&#39;(?P<no>\d+?)\.\n(?P<original>.+?)\n(?P<translate>.+?)\n&#39;
    # 编译
    pattern = re.compile(REGEXP)
    # 匹配
    rs = pattern.finditer(line)
    # 组装结果
    for r in rs:
        print(r.groupdict())
        sentences.append(r.groupdict())
    return sentences


if __name__ == "__main__":
    # 连接网易有道词典
    app = Application(backend="uia").connect(process=processId)
    # 获取需要的窗口
    win = app.window(class_name="RICHEDIT50W")

    # 输入词汇列表
    input_words = []
    # 输出词汇对象列表
    output_words = []
    # 打开输入文件,初始化输入词汇列表
    with open(input_path, "r", encoding="utf-8") as input_file:
        input_words = input_file.read().split("\n")

    for word in input_words:
        print("正在抓取单词: %s" % word)
        # 清空剪切板,这步很重要,防止重复复制
        pyperclip.copy("")
        # 将输入数据复制到剪切板
        pyperclip.copy(word)
        # 定位到输入框(采用坐标定位,定位到大致位置即可)
        mouse.click(coords=(2400, 80))
        # 模拟按键操作:全选 删除 粘贴 回车(触发查询)
        keyboard.send_keys("^a{DELETE}^v{ENTER}")
        # 清空剪切板,这步很重要,防止重复复制
        pyperclip.copy("")
        # 鼠标左键点击,这个操作只是为了把鼠标移动到这里
        mouse.click(button="left", coords=(2200, 330))
        # 模拟键盘 CTRL+A CTRL+C,直接全选所有的例句(这里会多选一部分内容,待会再处理)
        keyboard.send_keys("^a^c")
        # 暂停一会儿,不做操作的太快
        time.sleep(random.random() * 2 + 1)
        # pywinauto 复制的内容是在系统的剪切板里面的,所以需要其它库读取
        content = pyperclip.paste()
        # 对内容进行简单的预处理后,加入output_words
        try:
            lines = line_process(content)
        except BaseException as exp:
            print(exp)
            # 如果抓取出现问题,说明被网易抓了现行,直接退出即可。
            break

        sentences = to_list(lines)
        if not sentences:
            print("获取例句为空, 可能是数据格式错误.")
            break
        output_words.append({
            "word": word,
            "example": sentences,
        })
        # 模拟暂停一个较长的随机时间,没有必要追求速度,平稳运行即可。
        time.sleep(random.random() * 3 + 3)
        # 清空剪切板,这步很重要,防止重复复制
        pyperclip.copy("")

    # 抓取完毕一个文件的内容后,然后一次性写入即可。
    # 之前的写法是一个单词写入一次,会造成太多的IO次数,浪费性能!
    with open(output_path, "a+", encoding="utf-8") as output_file:
        output_file.write(json.dumps(
            output_words, ensure_ascii=False, indent=4))

        # 错误单词记录
        with open(error_path, "w", encoding="utf-8") as err_file:
            err_file.writelines("\n".join(error_words))
Copy after login

Demonstration If you want to start this code, it is quite complicated. I will just list the steps required here, hoping to help. Interested students.

  1. Modify dir_path and prepare an input.txt file below.

  2. Get the ID of the Youdao Dictionary process.

  3. Get the coordinates of the word input box and get the coordinates of the copy and paste location.

  4. Adjust the Youdao dictionary interface to the example sentence.

To start the project, you need an input.txt file. Here is the file I tested.

##sophisticated

centralization
phenomenon
internationalization
radioactive

I obtained the process pid through the task manager, you can also access it through other methods. Or the simplest is to use Inspect and Spy, I am lazy here , how to save trouble directly.

Steps and methods to implement automated collection tasks using Python and pywinauto

The coordinates of the word input box, the coordinates of the copy and paste location. The first coordinate is to position the input box, and then the program will Copy the word and press the Enter key, and then the content will be queried. Then move the mouse to the second coordinate, here just move it to the blank space below, and then perform a select-all CTRL A operation. This way All the content of a word has been obtained.

Steps and methods to implement automated collection tasks using Python and pywinauto

Adjust Youdao to this position, first query a word, select an example sentence, and then keep this interface unchanged.

Steps and methods to implement automated collection tasks using Python and pywinauto

The last step is the execution of the program. The recorded GIF has been accelerated. In fact, when it is executed, a delay is deliberately added to prevent it from being discovered prematurely. .

Steps and methods to implement automated collection tasks using Python and pywinauto

Console output

Steps and methods to implement automated collection tasks using Python and pywinauto

##output.json file

The above is the detailed content of Steps and methods to implement automated collection tasks using Python and pywinauto. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles