Python 如何在Robot Framework中比较两个字符串是否相等

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17838669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:17:51  来源:igfitidea点击:

How to compare two strings equal or not in Robot Framework

pythonwebdriverselenium-webdriverrobotframework

提问by Vamsi Reddy

How to compare two strings equal or not in Robot Framework. For example:

如何在 Robot Framework 中比较两个字符串是否相等。例如:

${xyz}=    Get Text    xpath=/html/body/div/div[2]/div[3]/div/div/div/div/h3
${abc}=    Get Text    xpath=/html/body/div/div[2]/div[4]/div/div/div/div/h3

These xpath values are getting different strings. So how to compare there strings equal or not?

这些 xpath 值正在获取不同的字符串。那么如何比较字符串是否相等呢?

Is it correct way to storing the values in variable in Robot Framework?

在 Robot Framework 中将值存储在变量中是否正确?

回答by mr2ert

Yes, that is the correct way of storing variables. Though you can also do it without the equal sign:

是的,这是存储变量的正确方法。虽然你也可以不使用等号来做到这一点:

${xyz}    Get Text    xpath=/html/body/div/div[2]/div[3]/div/div/div/div/h3
${abc}    Get Text    xpath=/html/body/div/div[2]/div[4]/div/div/div/div/h3

Now that you have the two different strings assigned to variables, you can simply do:

现在您已将两个不同的字符串分配给变量,您可以简单地执行以下操作:

Should Be Equal As Strings    ${xyz}    ${abc}

You can see the documentation for Should Be Equal As Stringshere.

您可以在Should Be Equal As Strings此处查看文档。

回答by Todor Minakov

An alternative to Should Be Equal As Stringsis to use Should Be True- it evaluates the provided argument as python expression (e.g. "something that can be substituted with a value") and fails if it turns up False:

另一种方法Should Be Equal As Strings是使用Should Be True- 它将提供的参数评估为 python 表达式(例如“可以用值替换的东西”),如果出现则失败False

Should Be True     """${variable 1}""" == """${variable 1}"""

It's a good practice to use triple quoteswhen you don't have control over the values (e.g. when taken from external source - a web page) - this construct permits the value to have quotes or newlines in it, without causing syntax error.

当您无法控制值时(例如从外部源 - 网页中获取时),使用三重引号是一个很好的做法- 此构造允许值中包含引号或换行符,而不会导致语法错误。

Though this approach can be a bit cumbersome for simple checks, it is quite powerful - you can use whatever python provides. For example, if the check should be case insensitive:

虽然这种方法对于简单的检查来说可能有点麻烦,但它非常强大——你可以使用 python 提供的任何东西。例如,如果检查不区分大小写:

Should Be True     """${variable 1}""".lower() == """${variable 1}""".lower()

Or if any starting/trailing whitespace is insignificant:

或者,如果任何起始/尾随空格无关紧要:

Should Be True     """${variable 1}""".strip() == """${variable 1}""".strip()

Or, is one string a part of another:

或者,一个字符串是另一个字符串的一部分:

Should Be True     """${variable 1}""" in """${variable 1}"""