Search code examples
rubywatir

How to mark a certain part of the text in watir?


Hello is there something that can only mark a certain part of the text? I can not find the right solution anywhere.

I tried: double_click, flash, select_text didn't work for me.

This works, but this mark everything : browser.send_keys [:control, 'a']

I added picture of example, what i want to do. Thank you for your answers. The red rectangle shows the markings


Solution

  • You can use the Element#select_text method. Note that prior to Watir 6.8, you will need to manually include the extension (method).

    Here is a working example using the Wikipedia page:

    require 'watir'
    require 'watir/extensions/select_text' # only include this if using Watir 6.7 or prior
    
    browser = Watir::Browser.new
    browser.goto('https://en.wikipedia.org/wiki/XPath')
    browser.body.select_text('XPath may be used')
    sleep(5) # so that you can see the selection
    

    Note that this will highlight the first match. You may want to restrict searching a specific element rather than the entire body.

    Here is another example using ckeditor.com:

    require 'watir'
    require 'watir/extensions/select_text' # only include this if using Watir 6.7 or prior
    
    browser = Watir::Browser.new
    browser.goto('ckeditor.com/')
    frame = browser.iframe(class: 'cke_wysiwyg_frame')
    frame.p.select_text('Bake the brownies')
    browser.link(href: /Bold/).click
    sleep(10)