如何在Robot Framework中用数据结构传递Selenium选项避免属性错误
解决RobotFramework中用数据结构传递Selenium浏览器选项的问题
问题场景
想要通过数据结构给Selenium的Open Browser接口传递浏览器选项,根据库文档说明,options参数接受Any类型,理论支持列表、字典或其组合。目前用长字符串形式传递是可行的:
add_argument("--no-sandbox"); add_argument("--disable-web-security"); add_argument("--disable-software-rasterizer"); add_argument("--proxy-server=http://10.10.10.10:80")
但尝试用如下列表嵌套字典的结构传递时,触发报错:
[{'add_argument': ['--no-sandbox']}, {'add_argument': ['--disable-web-security']}, {'add_argument': ['--disable-software-rasterizer']}, {'add_argument': ['--proxy-server=http://10.10.10.10:80']}]
报错信息:
AttributeError: 'list' object has no attribute 'capabilities'
当前环境:
- RobotFramework 7.0
- RobotFramework-SeleniumLibrary 6.2.0
- Selenium 4.18.1
- Python 3.12
自行尝试的代码:
${arguments} Create List ${options} Create List Append To List ${options} --no-sandbox Append To List ${options} --disable-web-security Append To List ${options} --disable-software-rasterizer Append To List ${options} --proxy-server=http://10.10.10.10:80 FOR ${elem} IN @{options} ${elem_list} Create list ${elem} ${dict} Create Dictionary add_argument ${elem_list} Append To List ${arguments} ${dict} END Log To Console ${arguments} ${current_open_window}= Open Browser browser=Chrome options=add_argument("--no-sandbox"); add_argument("--disable-web-security"); add_argument("--disable-software-rasterizer"); add_argument("--proxy-server=http://10.10.10.10:80")
解决方案
问题核心是传递的结构不符合SeleniumLibrary的预期——它需要的是单个字典,而非字典组成的列表。正确结构是把所有add_argument的参数整合到同一个字典的列表值中,格式为{'add_argument': [参数1, 参数2, ...]}。
修改后的代码:
# 构建所有浏览器参数的列表 ${option_list} Create List Append To List ${option_list} --no-sandbox Append To List ${option_list} --disable-web-security Append To List ${option_list} --disable-software-rasterizer Append To List ${option_list} --proxy-server=http://10.10.10.10:80 # 创建符合要求的options字典 ${browser_options} Create Dictionary add_argument ${option_list} # 传递字典给Open Browser接口 ${current_open_window}= Open Browser browser=Chrome options=${browser_options}
原理说明
SeleniumLibrary的options参数接受的字典结构,是将Selenium浏览器选项的方法名(如add_argument)作为键,对应的参数列表作为值。如果传递多个字典组成的列表,库无法将其识别为有效的浏览器选项对象,因此抛出'list' object has no attribute 'capabilities'错误——因为它期望的是能生成浏览器选项的结构化数据,而非普通列表。
内容的提问来源于stack exchange,提问作者Edwin
相关产品推荐
相关产品推荐

