1

Want to locate a string with two consecutive whitespace

like in page http://notepad.cc/manele85

string "Google" has two consecutive whitespace between 'o' and 'g'

my code:

require 'rubygems'
require 'watir'
require 'watir-webdriver'

b = Watir::Browser.new :firefox

b.goto "http://notepad.cc/manele85"
puts b.div(:text => "Goo  gle").text

outputs:

unable to locate element, using {:text=>"Goo  gle", :tag_name=>"div"} (Watir::Exception::UnknownObjectException)

Anyone can help?

Thanks

1 Answer 1

0

Watir normalize's spaces when locating elements by text. If you set $DEBUG to true, you can see that Watir is creating the following XPath for b.div(:text => "Goo gle"):

.//div[normalize-space()='Goo  gle']

Because of the normalize-space, Watir will treat multiple consecutive spaces as a single space.

As a result, when locating the element, you should remove the consecutive spaces in the locator:

b.div(:text => "Goo gle").exists?
#=> true

b.div(:text => "Goo gle").text
#=> "Goo gle"

If you do want to locate the element using the multiple spaces, you will have to get an element collection and check the text values:

div = b.divs.find { |div| div.text == 'Goo gle' }
div.text
#=> "Goo gle"
2
  • Hi Justin, it works! And want to know more about this: why Watir normalize's spaces? Is there a way to turn it off?
    – DarWcy
    Dec 29, 2014 at 14:44
  • I would guess that Watir normalizes spaces since the browser usually displays multiple consecutive spaces as a single space. There is no way to turn off the normalization (other than monkey patching). However, you could create a custom locator using find (example added to answer).
    – Justin Ko
    Dec 29, 2014 at 18:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.