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

Robot Framework导入自定义库Shop.py报错:RobotNotRunningError

解决Robot Framework自定义库导入时的RobotNotRunningError问题

问题重现

在PyCharm中导入自定义库../CustomeLibrary/Shop.py时触发错误:

Unresolved library: ../CustomeLibrary/Shop.py. Error generating libspec: Initializing library 'Shop' with no arguments failed: RobotNotRunningError: Cannot access execution context

自定义库代码尝试在__init__方法内获取SeleniumLibrary实例,环境配置为Python 3.10.1、Robot Framework 6.0.1、robotframework-seleniumlibrary 6.0.0。

错误原因

PyCharm的Robot Framework插件生成库规范文件(libspec)时,会提前初始化自定义库。而BuiltIn().get_library_instance()依赖Robot Framework的执行上下文,初始化阶段该上下文尚未创建,因此抛出RobotNotRunningError。

另外原代码存在两处小问题:

  • 循环变量名拼写错误:productsTite → productsTitle
  • XPath拼接方式不规范,易引发语法错误

解决方案

1. 延迟初始化SeleniumLibrary实例

不在__init__中直接获取实例,而是在关键字首次执行时再获取,避开libspec生成阶段的上下文缺失问题。

2. 修正代码错误

修改后的Shop.py代码如下:

from robot.api.deco import library, keyword
from robot.libraries.BuiltIn import BuiltIn

@library
class Shop:
    def __init__(self):
        self.selLib = None  # 先初始化空对象,不立即获取实例

    @keyword
    def add_items_to_cart_and_checkout(self, productsList):
        # 首次执行关键字时获取SeleniumLibrary实例
        if not self.selLib:
            self.selLib = BuiltIn().get_library_instance("SeleniumLibrary")
        
        i = 1
        productsTitles = self.selLib.get_webelements("xpath://*[@class='card-title']")
        for productsTitle in productsTitles:
            if productsTitle.text in productsList:
                # 使用f-string简化XPath拼接,避免语法错误
                self.selLib.click_button(f"xpath:(//*[@class='card-footer'])[{i}]/button")
            i += 1

3. 确保路径可识别

如果PyCharm仍提示库未解析,可执行以下操作:

  • 将CustomeLibrary文件夹标记为PyCharm的Sources Root(右键文件夹 → Mark Directory as → Sources Root)
  • 或在测试套件中使用绝对路径导入库,确保Python能找到该文件

验证步骤

  1. 替换修改后的Shop.py到对应目录
  2. 刷新PyCharm的Robot Framework库列表(可通过插件面板刷新)
  3. 编写测试用例时,确保已先导入SeleniumLibrary,再调用自定义关键字Add items to cart and checkout

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:41:44