使用RBFW解决Tosca Puzzle 41036(标题:TABLE SEARCH)遇到的代码问题:String.STRIP STRING无法移除全部指定字符
问题分析与解决方案
首先,你遇到的核心问题是对String.STRIP STRING关键字的功能理解有误——这个关键字只会移除字符串开头和结尾匹配的字符,而不会处理字符串中间的字符。这就是为什么你指定了一堆字符,但中间的tains、"这些内容没被移除的原因。
正确的解决思路
要全局移除所有指定的字符,你需要使用String.REPLACE STRING关键字(或者正则版本的String.REPLACE STRING WITH REGEX)来替换掉不需要的内容,而不是依赖只处理首尾的STRIP STRING。
修改后的代码示例
这里提供两种可行的写法:
方法1:逐个替换指定字符(直观易读)
*** Settings *** Library Browser Library String # title = TABLE SEARCH *** Variables *** *** Test Cases *** Example Test 70310 OPEN BROWSER https://obstaclecourse.tricentis.com/Obstacles/41036 ${txt}= GET TEXT //span[contains(text(),'Table contains')] # 逐步移除不需要的内容 ${cleaned_txt}= String.REPLACE STRING ${txt} Table contains ${EMPTY} ${cleaned_txt}= String.REPLACE STRING ${cleaned_txt} " ${EMPTY} ${cleaned_txt}= String.REPLACE STRING ${cleaned_txt} ? ${EMPTY} ${cleaned_txt}= String.REPLACE STRING ${cleaned_txt} ( ${EMPTY} ${cleaned_txt}= String.REPLACE STRING ${cleaned_txt} ) ${EMPTY} ${cleaned_txt}= String.REPLACE STRING ${cleaned_txt} / ${EMPTY} ${cleaned_txt}= String.STRIP STRING ${cleaned_txt} # 最后清理首尾残留的空格 LOG TO CONSOLE ${cleaned_txt} FILL TEXT xpath=//input[@id='resulttext'] ${cleaned_txt} Get Text xpath=//body *= You solved this automation problem.
方法2:使用正则表达式一次性替换(更简洁)
用正则匹配所有需要移除的字符,一次完成替换:
*** Settings *** Library Browser Library String # title = TABLE SEARCH *** Variables *** *** Test Cases *** Example Test 70310 OPEN BROWSER https://obstaclecourse.tricentis.com/Obstacles/41036 ${txt}= GET TEXT //span[contains(text(),'Table contains')] # 正则匹配所有要移除的内容:字母、引号实体、问号、括号、斜杠 ${cleaned_txt}= String.REPLACE STRING WITH REGEX ${txt} [A-Za-z"?()/] ${EMPTY} ${cleaned_txt}= String.STRIP STRING ${cleaned_txt} # 清理首尾空格 LOG TO CONSOLE ${cleaned_txt} FILL TEXT xpath=//input[@id='resulttext'] ${cleaned_txt} Get Text xpath=//body *= You solved this automation problem.
原代码无效的原因
原代码里的String.STRIP STRING只会处理字符串首尾的匹配字符,比如你的原始字符串是"Table contains "15"? (True/False)",它只会移除开头的T、a等连续指定字符,以及结尾的e、s等,中间的字符完全不会被触碰,所以才会得到tains "15"? (True/Fals)这样的结果。
内容的提问来源于stack exchange,提问作者LTL
相关产品推荐
相关产品推荐

