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

解决Robot Framework中TypeError: 期望str实例却得到WebElement错误

Robot Framework + Selenium 移除购物车商品报错:TypeError: sequence item 1: expected str instance, WebElement found

你遇到的类型错误核心是代码中存在WebElement对象被当作字符串处理的情况,同时代码语法不完整也会引发变量解析异常,以下是具体解决步骤:

  • 补全代码语法闭合
    你提供的代码里FOR循环和IF语句都缺少END标记,这会导致Robot Framework解析出错,修复后的完整代码如下:

    Remove unexpected cart items
        [Arguments]    @{expected_items}
        ${cart_items}=    Get WebElements    css:.cart_item
        FOR    ${item}    IN    @{cart_items}
            ${name}=    Execute Javascript    return arguments[0].querySelector(".inventory_item_name").textContent;    ${item}
            ${is_expected}=    Run Keyword And Return Status    List Should Contain Value    ${expected_items}    ${name}
            IF    not ${is_expected}
                Log    Removing unexpected item: ${name}
                ${remove_button}=    Execute Javascript    return arguments[0].querySelector("button");    ${item}
                Click Element    ${remove_button}
            END
        END
    
  • 替换JS获取文本的方式(更稳定)
    直接用JS获取文本可能存在类型返回异常,改用Robot Framework原生关键字获取子元素文本:

    # 替换原${name}的获取逻辑
    ${name_element}=    Find Element    ${item}    css:.inventory_item_name
    ${name}=    Get Text    ${name_element}
    
  • 检查预期商品列表的传入值
    调用Remove unexpected cart items关键字时,确保传入的@{expected_items}是纯字符串列表(如商品名称),不要混入WebElement对象。示例调用:

    Remove unexpected cart items    背包    运动鞋
    
  • 替换JS获取按钮的方式
    改用原生关键字定位按钮,避免JS返回元素的潜在问题:

    # 替换原${remove_button}的获取逻辑
    ${remove_button}=    Find Element    ${item}    css:button
    Click Element    ${remove_button}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 21:34:55