You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python解析Robot文件并提取库、关键字及对应参数

解析Robot文件获取库列表与关键字参数

需求目标

解析Robot测试文件,完成两项任务:

  1. 提取文件中声明的所有库(包含库的初始化参数)
  2. 提取测试用例中的关键字及其对应的参数

原始Robot文件内容

*** Settings ***
Documentation     OpenGoogle
Library           SeleniumLibrary    timeout=10
Test Teardown     Close Browser

*** Test Cases ***
OpenGoogle Test
    Open Available Browser    https://www.google.com/
    Maximize Browser Window
    Input Text    /html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input    python tutorial
    Click Element    /html/body/div[1]/div[3]/form/div[1]/div[1]/div[4]/center/input[1]
    Sleep    3s

初始尝试的Python代码

from robot.api import TestSuiteBuilder


def parse_robot_file2(file_path):
    suite_builder = TestSuiteBuilder()
    suite = suite_builder.build(file_path)

    for testcase in suite.tests:
         
         print(f"{testcase}")
       
         for step in testcase.keywords:
             keyword = step.name
             arguments = step.args
             print(f"{keyword}({', '.join(arguments)})")

parse_robot_file2("robot_scriptt.robot")

初始代码运行输出

Open Available Browser(https://www.google.com/)
Maximize Browser Window()
Input Text(/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input, python tutorial)
Click Element(/html/body/div[1]/div[3]/form/div[1]/div[1]/div[4]/center/input[1])
Sleep(3s)
Close Browser()

优化后的完整实现代码

初始代码仅提取了关键字信息,以下是补充库列表提取的完整代码:

from robot.api import TestSuiteBuilder


def parse_robot_file(file_path):
    suite_builder = TestSuiteBuilder()
    suite = suite_builder.build(file_path)

    # 提取并打印库列表
    print("=== 已加载的库 ===")
    for lib in suite.resource.imports:
        if lib.type == 'Library':
            lib_name = lib.name
            lib_args = ', '.join(lib.args)
            print(f"{lib_name}({lib_args})" if lib_args else lib_name)

    # 提取并打印测试用例的关键字与参数
    print("\n=== 测试用例关键字详情 ===")
    for testcase in suite.tests:
        print(f"\n测试用例:{testcase.name}")
        for step in testcase.keywords:
            keyword = step.name
            arguments = ', '.join(step.args)
            print(f"  {keyword}({arguments})")


parse_robot_file("robot_scriptt.robot")

优化代码的运行输出

=== 已加载的库 ===
SeleniumLibrary(timeout=10)

=== 测试用例关键字详情 ===

测试用例:OpenGoogle Test
  Open Available Browser(https://www.google.com/)
  Maximize Browser Window()
  Input Text(/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input, python tutorial)
  Click Element(/html/body/div[1]/div[3]/form/div[1]/div[1]/div[4]/center/input[1])
  Sleep(3s)
  Close Browser()

内容的提问来源于stack exchange,提问作者Kuldeep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 11:15:16