Robot Framework Browser Library列名验证严格模式违规报错求助
Robot Framework Browser Library批量验证列名问题解决
我在用Robot Framework的Browser Library做业务应用自动化测试时,最初通过逐个XPath定位元素验证列名的方式是可行的:
Get Text //span[text()='CPF'] contains CPF Get Text //span[text()='CNS'] contains CNS Get Text //span[text()='Nascimento'] contains Nascimento Get Text //span[text()='Nome'] contains Nome Get Text //span[text()='Nome da mãe'] contains Nome da mãe Get Text //span[text()='UF'] contains UF Get Text //span[text()='Município'] contains Município Get Text //span[text()='Carteiras'] contains Carteiras
为了优化实现,尝试用CSS选择器批量定位元素,但触发了严格模式违规错误:
${element} Set Variable css=thead tr td span Wait For Elements State ${element} ... visible 5 Get Text ${element} contains CPF Get Text ${element} contains CNS # 后续验证代码省略
错误信息:
Error: locator.waitFor: Error: strict mode violation: locator('div .novaListagem table thead tr td span') resolved to 8 elements:
- CPF aka getByRole('cell', { name: 'CPF', exact: true }).locator('span')
- CNS aka getByText('CNS')
- Nascimento aka getByText('Nascimento', { exact: true })
- Nome aka getByRole('cell', { name: 'Nome', exact: true }).locator('span')
- Nome da mãe aka getByText('Nome da mãe')
- UF aka getByText('UF')
- Município aka getByText('Município')
- Carteiras aka getByText('Carteiras')
问题原因
Browser Library默认启用严格模式,当定位器匹配到多个元素时,单个元素操作(如Get Text)会报错,因为无法确定要操作哪一个元素。
解决方案
方案1:批量获取文本后统一验证(推荐)
通过Get Texts(复数形式)一次性获取所有表头元素的文本,再和预期列名列表对比,既高效又简洁。
# 定义预期列名列表(对应中文:CPF、CNS、出生日期、姓名、母亲姓名、州、城市、证件) ${expected_columns} Create List CPF CNS Nascimento Nome Nome da mãe UF Município Carteiras # 等待所有表头元素可见 Wait For Elements State css=thead tr td span visible 5 # 批量获取所有表头span的文本 ${actual_columns} Get Texts css=thead tr td span # 验证所有预期列都存在于实际列中(不要求顺序) FOR ${col} IN @{expected_columns} Should Contain ${actual_columns} ${col} END # 如果要求列顺序和数量完全一致,改用下面的验证 # Should Be Equal As Lists ${actual_columns} ${expected_columns}
方案2:通过索引逐个定位元素
如果需要保留逐个验证的逻辑,可以用CSS的:nth-child()伪类或元素索引来定位单个元素,避开严格模式限制。
Wait For Elements State css=thead tr td span visible 5 # 通过:nth-child(index)定位单个元素(索引从1开始) Get Text css=thead tr td span:nth-child(1) contains CPF Get Text css=thead tr td span:nth-child(2) contains CNS Get Text css=thead tr td span:nth-child(3) contains Nascimento Get Text css=thead tr td span:nth-child(4) contains Nome Get Text css=thead tr td span:nth-child(5) contains Nome da mãe Get Text css=thead tr td span:nth-child(6) contains UF Get Text css=thead tr td span:nth-child(7) contains Município Get Text css=thead tr td span:nth-child(8) contains Carteiras
方案3:关闭严格模式(不推荐)
可以在定位器后添加>> strict=false关闭严格模式,但此时Get Text只会返回第一个匹配元素的文本,无法实现所有列的验证,仅适合单元素操作场景,不建议用于本次需求。
内容的提问来源于stack exchange,提问作者Alexandre Araújo Fagundes
相关产品推荐
相关产品推荐

