2

How can we select a text in Webpage using Selenium? I am trying to test one Web application using selenium webdriver.

I have defiend seperate methods in one class file for eg, 1) To Open an Browser 2) Select dropdown values 3) Switch to new window etc., will call the method where ever needed with that i want to create one method to select a text.

I would like to know how to achieve it instead of using the following Snippet, My codes are here:

Actions act_higlight = new Actions(driver);
act_higlight.moveToElement(element, 2, 15)
   .clickAndHold()
   .moveByOffset(30, 0)
   .release()
   .perform(); 

Because sometimes my text will be two lines sometime 5 lines, I am not suppose to touch my Method once it is declared ie., I cannot go and change this (.moveByOffset(30, 5)) frequently

So if any of you could guide me on this will be greatly appreciated. I have been stuck in this for quite few days now.. Just look at this screenshot this is how i want it.enter image description here Thanks in Advance.

3
  • Share your html code for text Commented Apr 18, 2017 at 8:26
  • This is the application url: spreadsheetpage.com/index.php/file/C35/P10 and I want to select this text "Animated Color Scales". Commented Apr 18, 2017 at 8:40
  • Which Which text you want ? Commented Apr 18, 2017 at 8:40

1 Answer 1

4

You can simply find header by CSS selector h1.tiptitle and get required text with getText() method:

String title = driver.findElement(By.cssSelector('h1.tiptitle')).getText();

If you want just to highlight the text (for example, to make screenshot) you can apply JavaScript to change elements' style:

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.querySelector('h1.tiptitle').style.background='blue';");
jse.executeScript("document.querySelector('h1.tiptitle').style.color='white';");

Update

Try below code and let me know the result

jse.executeScript("function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

var el = document.querySelector('h1.tiptitle');
selectElementContents(el);");
Sign up to request clarification or add additional context in comments.

3 Comments

You want just to highlight text? What you want to do next after you "select" your text?
Next step is to Copy the selected Text
I need to select it using mouse not using getText().

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.