How to check if a text is highlighted on the page using Selenium?

可紊 提交于 2020-08-25 09:52:39

问题


1> What does highlighted text means? Suppose you browse any page , select any text on that page using mouse or some other means. Let say "Hello" , "Sign Up "text is highlighted. Please correct my understanding if its wrong.

2> I tried the below code to get CssValue of color and background-color. Using the given code:

    driver.get("https://facebook.com");
    String textColor = driver.findElement(By.xpath("//*[@id='pageFooter']/div[3]/div/span")).getCssValue("color");
    String bkgColor = driver.findElement(By.xpath("//*[@id='pageFooter']/div[3]/div/span")).getCssValue("background-color");
    System.out.println("TextColor : " + textColor );
    System.out.println("Background Color : " + bkgColor);

output:-

TextColor : rgba(115, 115, 115, 1)
Background Color : transparent

*TextColor gives the color of text.

** For highlighting i am using Robot class to send Ctrl+A , though its selecting entire page, but it should output some different value. In that case also it's giving the text color only as above output.

Please let me know if i am doing right or is my understanding about highlighted text is correct.


回答1:


You cannot do it with Selenium by itself, but you can do it executing javascript with Selenium. Js is pretty simple:

window.getSelection().toString();

enter image description here

So just:

((JavascriptExecutor)driver).executeScript("return window.getSelection().toString();");

PS will not work in <=IE8 (will provide how if you'll need)




回答2:


The CSS style of the element with the selected text would not change after you select it's text in the browser. What you can do is to get the current "active" element and see if it is the desired one:

WebElement desiredElement = driver.findElement(By.xpath("//*[@id='pageFooter']/div[3]/div/span"));
WebElement activeElement = driver.switchTo().activeElement();


来源:https://stackoverflow.com/questions/29475414/how-to-check-if-a-text-is-highlighted-on-the-page-using-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!