鉴于我有:
b = Watir::Browser.new
b.goto 'google.com'
string = "div(:id => 'main')"
string
由用户提供。
有没有办法使用指定的字符串,它描述了如何定位元素,在浏览器中找到元素?换句话说,我如何执行字符串,如下所示:
b.div(:id => 'main')
我尝试使用b.send(string)
,但这只适用于string = url
:
b = Watir::Browser.new
b.goto 'google.com'
string = "div(:id => 'main')"
b.send(string)
#=> "https://www.google.com"
在查找元素时,如string = "div(:id =>'main')"
,我得到一个未定义的方法错误:
b = Watir::Browser.new
b.goto 'google.com'
string = "div(:id => 'main')"
b.send(string)
#=> undefined method `div(:id =>'main')' for #
答案 0 :(得分:3)
如果你把Watir命令作为字符串,我认为命令会变得更复杂。例如:
# Locating based on a partial match (ie regexp)
string = "div(:id => /main/)"
# A locator value with non-word characters
string = "link(:href => 'some/url')"
# Locating nested elements
string = "div(:id => 'main').span(:class => 'text')"
手动解析这些类型的字符串比仅扫描字符串更复杂。例如,在正则表达式示例中,只扫描单词最终会为您提供定位器{"id"=>"main", :tag_name=>"div"}
。请注意,id现在正在寻找“main”的完全匹配,这不是字符串所需的。
因此,我认为您应该使用instance_eval
,这将消除手动解析的需要:
require 'watir-webdriver'
b=Watir::Browser.new
b.goto 'https://www.google.com'
# Original string
string = "div(:id =>'main')"
p b.instance_eval(string)
#=> #<Watir::Div:0x61221438 located=false selector={:id=>"main", :tag_name=>"div"}>
# Locating based on a partial match (ie regexp)
string = "div(:id => /main/)"
#=> #<Watir::Div:0x42afd800 located=false selector={:id=>/main/, :tag_name=>"div"}>
# A locator value with non-word characters
string = "link(:href => 'some/url')"
p b.instance_eval(string)
#=> #<Watir::Anchor:0x2b625f26 located=false selector={:href=>"some/url", :tag_name=>"a"}>
# Locating nested elements
string = "div(:id => 'main').span(:class => 'text')"
p b.instance_eval(string)
#=> #<Watir::Span:0x..fb341cd56 located=false selector={:class=>"text", :tag_name=>"span"}>
答案 1 :(得分:2)
请尝试以下操作:
require 'watir-webdriver'
b=Watir::Browser.new
b.goto 'https://www.google.com'
string = "div(:id =>'main')"
meth,*selector_arr = string.scan(/\w+/)
# => ["div", "id", "main"]
selector_hsh = Hash[*selector_arr]
p b.send(meth,selector_hsh)
# >> #<Watir::Div:0x5b248f1c located=false selector={"id"=>"main", :tag_name=>"div"}>