3

In following html

<p>
<strong>Name:</strong>
12121
</p>

How can I access the "12121" text using Watir?

3
  • " <p> <strong>Name:</strong> 12121 </p> Commented Jan 9, 2013 at 9:22
  • Are you using watir-classic (ie just using IE) or watir-webdriver (ie also using Firefox or Chrome)? Commented Jan 9, 2013 at 14:41
  • watir-webdriver (ie also using Firefox or Chrome) Commented Jan 10, 2013 at 4:41

3 Answers 3

3

To get subtext 12121 use Regular expressions.
gsub performs a search-and-replace operation. It will search for all non-digit characters(/\D/) and replace with the given string. In this case we are not giving any string to replace.


=browser.p.text.gsub(/\D/, "")
=> "12121"

Sign up to request clarification or add additional context in comments.

Comments

1

browser.p.text returns "Name: 12121" and browser.p.strong.text returns "Name:".

> browser.p.text
 => "Name: 12121" 

> browser.p.strong.text
 => "Name:" 

To get 12121 one (or more) of String methods could be used, for example String#split and then String#lstrip.

> long = b.p.text
 => "Name: 12121" 

> short = b.p.strong.text
 => "Name:" 

> long.split(short)
 => ["", " 12121"] 

> long.split(short)[1]
 => " 12121" 

> long.split(short)[1].lstrip
 => "12121"

2 Comments

that I have already tried, I was looking for some alternative to do
You should said it in the question what you have already tried. That would save me some time.
1

While I think that parsing the paragraph elements text is the easiest, if you really just want to get the text node, you could use javascript.

If you know that the text will always be the last part of the paragraph, you can do:

browser.execute_script("return arguments[0].lastChild.nodeValue", browser.p)
#=> "12121"

If the structure can change and you want all text of the paragraph element, without the children element's text, you can generalize it:

get_text_node_script = <<-SCRIPT
    var nodes = arguments[0].childNodes;
    var result = "";
    for(var i = 0; i < nodes.length; i++) {
        if(nodes[i].nodeType == Node.TEXT_NODE) {
            result += nodes[i].nodeValue; 
        }
    }   
    return result
SCRIPT

browser.execute_script(get_text_node_script, browser.p)
#=> "12121"

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.