I'm using Mechanize
to interact with a few web pages, and I'm trying to determine whether a given form submission resulted in an error.
我正在使用Mechanize与几个网页进行交互,我正在尝试确定给定的表单提交是否导致错误。
Right now I'm doing this:
现在我这样做:
agent.page.body.include?("I'm an error message!")
But I just discovered another error message. Since I don't want to do:
但我刚刚发现了另一条错误消息。既然我不想这样做:
agent.page.body.include?("I'm an error message!") || agent.page.body.include?("Another error message")
How can I determine whether the page body contains either error message?
如何确定页面正文是否包含错误消息?
2 个解决方案
#1
23
error_messages.any? { |mes| agent.page.body.include? mes }
#2
10
Alternatively, do it in one Regex pass:
或者,在一个Regex传递中执行:
error_messages = /I'm an error message!|Another error message/
if agent.page.body =~ error_messages
...
end
You'll need to ensure that you escape any error messages that contain special regex characters. To make it maintainable:
您需要确保转义包含特殊正则表达式字符的任何错误消息。为了使其可维护:
if agent.page.body =~ Regexp.union("foo", "bar", "jim.bob", "jam|jam")
...
end
You should only use this if you have tested and found the speed of Nakilon's answer is not enough, however. :)
你应该只使用它,如果你已经测试过,并且发现Nakilon答案的速度还不够。 :)
#1
23
error_messages.any? { |mes| agent.page.body.include? mes }
#2
10
Alternatively, do it in one Regex pass:
或者,在一个Regex传递中执行:
error_messages = /I'm an error message!|Another error message/
if agent.page.body =~ error_messages
...
end
You'll need to ensure that you escape any error messages that contain special regex characters. To make it maintainable:
您需要确保转义包含特殊正则表达式字符的任何错误消息。为了使其可维护:
if agent.page.body =~ Regexp.union("foo", "bar", "jim.bob", "jam|jam")
...
end
You should only use this if you have tested and found the speed of Nakilon's answer is not enough, however. :)
你应该只使用它,如果你已经测试过,并且发现Nakilon答案的速度还不够。 :)