smriti
smriti

Reputation: 1144

Select a text and perform a click action

I'd like to select some text and perform a click action - like in Winword where we click Bold after selecting some text...

I have to select the text and click on the <B> bold icon in the textarea.

Any idea on how to do this using Selenium/Webdriver?

Upvotes: 10

Views: 18916

Answers (5)

Att Righ
Att Righ

Reputation: 1789

You might prefer to directly interact with the javascript DOM - since this can select text.

The following code in python selects a single sup element (Chrome).

driver.execute_script("""
el = document.evaluate('//sup', document).iterateNext()
selection = document.getSelection()
selection.removeAllRanges()
range = document.createRange()
range.selectNode(el)
selection.addRange(range)
""")

Upvotes: 0

Rakshika Saravanan
Rakshika Saravanan

Reputation: 11

driver.navigate().to("https://leafground.com/input.xhtml"); WebElement cls= driver.findElement(By.xpath("//div[@class="ql-editor ql-blank"]")); cls.sendKeys("this is rakshika " + Keys.CONTROL + "a"); driver.findElement(By.xpath("//button[@class="ql-italic"]\r\n")).click();

Upvotes: 1

Siju Vasu
Siju Vasu

Reputation: 11

I tried with Action builder and played with offset. It worked for me.

Actions action = new Actions(driver);
action.moveToElement(wblmt,3,3).click().keyDown(Keys.SHIFT).moveToElement(wblmt,200, 0).click().keyUp(Keys.SHIFT).build().perform(); 

Upvotes: 1

Ho Nguyen
Ho Nguyen

Reputation: 1

I tried this way and it did not work. Here are the codes:

System.setProperty("webdriver.chrome.driver", "D:/chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.google.com.vn");
    driver.manage().window().maximize();

    WebElement text = driver.findElement(By.xpath("//*[contains(text(),'Google.com.vn')]"));
    Actions actions = new Actions(driver);
    actions.moveToElement(text, 10, 5).clickAndHold().moveByOffset(30, 0).release().perform();

I switched to JavascriptExecutor and it worked:

    System.setProperty("webdriver.chrome.driver", "D:/chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.google.com.vn");
    driver.manage().window().maximize();

    WebElement text = driver.findElement(By.xpath("//*[contains(text(),'Google.com.vn')]"));
    JavascriptExecutor js = (JavascriptExecutor) driver;

    js.executeScript("arguments[0].setAttribute('style', 'background: blue;');", text);

Upvotes: 0

Petr Janeček
Petr Janeček

Reputation: 38424

In Java, The Advanced User Interactions API has your answer.

// the element containing the text
WebElement element = driver.findElement(By.id("text"));
// assuming driver is a well behaving WebDriver
Actions actions = new Actions(driver);
// and some variation of this:
actions.moveToElement(element, 10, 5)
    .clickAndHold()
    .moveByOffset(30, 0)
    .release()
    .perform();

Upvotes: 9

Related Questions