質問

I am very new to Ruby and have run into something that I cannot figure out. I am trying to write a test that accesses a variable in javascript that tells what type of page the user has landed on, but I have NO idea how to do it. Any help or explanation would be very much appreciated. Here is the source (I need to access the value in s.prop5 on the page and make decisions based on that):

<script language="JavaScript"><!--
s.pageName="Outdoor : "
s.server=""
s.channel=""
//s.pageType=""
s.prop1=""
s.prop2=""
s.prop3=""
s.prop5="Department"
役に立ちましたか?

解決 2

If you get the html of the script tag, you can parse it using regular Ruby string methods to find the value you want.

Assuming the script tag is the first on the page, you can get the script tag's html with:

browser.script.html
#=> <script language=\"JavaScript\"><!--\ns.pageName=\"Outdoor : \"\ns.server=\"\"\ns.channel=\"\"\n//s.pageType=\"\"\ns.prop1=\"\"\ns.prop2=\"\"\ns.prop3=\"\"\ns.prop5=\"Department\"\n</script>

You could use a regular expression to find the value:

browser.script.html[/s.prop5="([^"]+)"/, 1]
#=> "Department"

Since there could be multiple script tags and script tags do not have a useful identifier, you will likely need to iterate through the script tags until the value is found:

script = browser.scripts.find { |script| script.html.include?('s.prop5') }
script.html[/s.prop5="([^"]+)"/, 1]
#=> "Department"

他のヒント

There's no need to write complex regular expressions to parse html to retrieve the values you need because Watir::Browser#execute_script allows you to return almost anything from JavaScript directly to Ruby.

Check out these specs for examples: https://github.com/watir/watirspec/blob/master/browser_spec.rb#L225-L246

You can do this with regular expressions:

src = '<script language="JavaScript"><!--
       s.pageName="Outdoor : "
       s.server=""
       s.channel=""
       //s.pageType=""
       s.prop1=""
       s.prop2=""
       s.prop3=""
       s.prop5="Department"'

pattern = /s\.prop5\s*=\s*"([^"]*)"/

page_type = pattern.match(src)[1]

This page has a lot of good information about using regexp in Ruby. You can do all kinds of awesome stuff in Ruby using regexp!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top