Search code examples
rubywatir

Why doesn't Watir find script tag by src attribute


Navigating to any page, I can review the scripts present with Watir:

b = Watir::Browser.new
b.goto "https://macys.com"
b.scripts.collect(&:src)
# => [ ..., "https://mathid.mathtag.com/d/i.js", ...]

The result is a large array of scripts, I've chosen one at random to find:

b.script(src: "https://mathid.mathtag.com/d/i.js").html
# => Watir::Exception::UnknownObjectException: timed out after 30 seconds, waiting for #<Watir::HTMLElement: located: false; {:xpath=>"//script[@src='https://mathid.mathtag.com/d/i.js']"}> to be located; Maybe look in an iframe?
# ...

But it never finds any script this way. Why? How can I detect the presence without investigating the scripts.collect(&:src)?


Solution

  • Watir is locating the element based on string matching what is present in the DOM. If you investigate the DOM, you'll see that the https: is not present, just the //mathid.mathtag.com/d/i.js. The browser driver translates that when queried about the attribute value to include the https, but Watir has no way to assume that when locating.

    This will work:

    browser.script(src: '//mathid.mathtag.com/d/i.js')