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

RobotFramework报错AttributeError: 'str'对象无_parent属性求助

问题:RobotFramework元素高亮报错AttributeError: 'str' object has no attribute '_parent'

问题描述

使用RobotFramework开展自动化测试时,想要实现页面元素高亮功能,编写了对应的Python高亮函数及Robot关键字,但运行测试脚本时出现错误:AttributeError: 'str' object has no attribute '_parent'。

相关代码

自定义Python高亮函数

import time

def highlight(element):
    """Highlights (blinks) a Selenium Webdriver element"""
    driver = element._parent
    def apply_style(s):
        driver.execute_script("arguments[0].setAttribute('style', arguments[1]);",
                              element, s)
    original_style = element.get_attribute('style')
    apply_style("background: yellow; border: 2px solid red;")
    time.sleep(.3)
    apply_style(original_style)

Common.robot代码

*** Settings ***
Library     SeleniumLibrary   15.0    5.0
Library    OperatingSystem
Library           highlight.py
Resource    ../LoginPage/LoginKW.robot

*** Variables ***
${URL}           https://www.involve.me/

*** Keywords ***
Start
    ${options}=  Evaluate        sys.modules['selenium.webdriver'].ChromeOptions()  sys, selenium.webdriver
    Log To Console                                 ${options}
    Create WebDriver    Chrome      chrome_options=${options}
    Go To          ${URL}
    ${handles}=  Get Window Handles
    Maximize Browser Window
    Verify Current URL
    ${SCREEN_TEXTS}  Read Json    ../../TestData/Involve_Test.json
    Set Global Variable    ${SCREEN_TEXTS}

Read Json
    [Documentation]    The function, with its' own keyword reads the json files.
    [Arguments]        ${file_path}
    ${JSONContent}     Get File     ${file_path}
    ${page}=           Evaluate        json.loads("""${JSONContent}""")    json
    [Return]           ${page}

Close My Browser
    Sleep  2s
    Close All Browsers

Click For Element
    [Arguments]                         ${element}
    Highlight                           ${element}
    Wait Until Element Is Visible       ${element}
    Click Element                       ${element}

Input For Text
    [Arguments]                         ${element}      ${input}
    Wait Until Element Is Visible       ${element}
    Highlight                           ${element}
    Input Text                          ${element}      ${input}

LoginTC.robot代码

*** Settings ***
Documentation       Test Case Login
Library             SeleniumLibrary
Resource            ../../PageObjects/LoginPage/LoginKW.robot
Resource            ../../PageObjects/Common/common.robot
Test Setup        Start  # Suitw Setup will run only once
Test Teardown      common.Close My Browser

*** Test Cases ***
Test Login
    sleep    3s
    Click Cookie
    Click On Link Login
    Enter Email                          xxxxxyyyyzzz@gmail.com
    Enter Password                       abcdefghijk3Only
    Click On Sign in button
    Is Text Displayed     ${SCREEN_TEXTS["ws_page_title"]}

报错信息

(venv) C:\Users\User\PycharmProjects\InvolvemeRobotFramework\TestCases\Login> robot LoginTC1.robot
LoginTC1 :: Test Case Login
Test Login                                                            <selenium.webdriver.chrome.options.Options object at 0x041902B0>
DevTools listening on ws://127.0.0.1:61649/devtools/browser/4914f52f-47f6-4632-a776-02045dda890c
https://www.involve.me/
..F.....[28328:8120:0508/220557.776:ERROR:device_event_log_impl.cc(222)] [22:05:57.777] USB: usb_device_handle_win.cc:1046 Failed to read descriptor from node connec
tion: A device attached to the system is not functioning. (0x1F)
Test Login                                                            | FAIL |
AttributeError: 'str' object has no attribute '_parent'

解决方案

问题根源

报错核心原因:传给Highlight函数的参数是元素定位字符串(如XPATH、ID这类定位表达式),但Python函数highlight期望接收的是Selenium的WebElement实例对象。字符串类型没有_parent属性,因此触发AttributeError。

解决方法(二选一即可)

方法1:修改Robot关键字,先获取WebElement对象再传递

无需修改Python代码,仅调整Robot关键字,先通过SeleniumLibrary获取元素实例,再传给Highlight:

Click For Element
    [Arguments]                         ${element}
    # 先获取WebElement实例
    ${web_element}=    Wait Until Element Is Visible       ${element}
    Highlight                           ${web_element}
    Click Element                       ${element}

Input For Text
    [Arguments]                         ${element}      ${input}
    # 先获取WebElement实例
    ${web_element}=    Wait Until Element Is Visible       ${element}
    Highlight                           ${web_element}
    Input Text                          ${element}      ${input}

方法2:修改Python函数,支持接收定位符和Driver

若希望直接传递定位字符串,可修改Python函数,让它接收Driver和定位符,内部先查找元素再执行高亮:

import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def highlight(driver, locator):
    """Highlights (blinks) a Selenium Webdriver element using locator"""
    # 解析Robot风格的定位符(比如"xpath=//xxx"或元组格式)
    if isinstance(locator, str):
        by, value = locator.split('=', 1)
        by = by.upper()
        from selenium.webdriver.common.by import By
        by = getattr(By, by)
        locator = (by, value)
    
    # 等待元素出现并获取
    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator))
    
    def apply_style(s):
        driver.execute_script("arguments[0].setAttribute('style', arguments[1]);",
                              element, s)
    original_style = element.get_attribute('style')
    apply_style("background: yellow; border: 2px solid red;")
    time.sleep(.3)
    apply_style(original_style)

同时修改Robot关键字的调用逻辑,传入Driver实例和定位符:

Click For Element
    [Arguments]                         ${element}
    ${driver}=    Get WebDriver Instance
    Highlight                           ${driver}    ${element}
    Wait Until Element Is Visible       ${element}
    Click Element                       ${element}

Input For Text
    [Arguments]                         ${element}      ${input}
    ${driver}=    Get WebDriver Instance
    Highlight                           ${driver}    ${element}
    Wait Until Element Is Visible       ${element}
    Input Text                          ${element}      ${input}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:19:58