java 如何使用 Selenium 检查页面上的文本是否突出显示?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29475414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a text is highlighted on the page using Selenium?
提问by workspace
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 "" , "Sign Up "text is highlighted. Please correct my understanding if its wrong.
1> 突出显示的文字是什么意思?假设您浏览任何页面,使用鼠标或其他方式选择该页面上的任何文本。假设“ ”,“注册”文本突出显示。如果有错误,请纠正我的理解。
2> I tried the below code to get CssValue of color and background-color. Using the given code:
2> 我尝试了下面的代码来获取颜色和背景颜色的 CssValue。使用给定的代码:
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.
*TextColor 给出文本的颜色。
** 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.
** 为了突出显示,我使用 Robot 类发送 Ctrl+A ,虽然它选择了整个页面,但它应该输出一些不同的值。在这种情况下,它也只提供如上输出的文本颜色。
Please let me know if i am doing right or is my understanding about highlighted text is correct.
如果我做得对,或者我对突出显示的文本的理解是否正确,请告诉我。
回答by Stan E
You cannot do it with Selenium by itself, but you can do it executing javascript with Selenium. Js is pretty simple:
您不能单独使用 Selenium 来完成它,但是您可以使用 Selenium 执行 javascript 来完成它。Js非常简单:
window.getSelection().toString();
So just:
所以就:
((JavascriptExecutor)driver).executeScript("return window.getSelection().toString();");
PS will not work in <=IE8 (will provide how if you'll need)
PS 在 <=IE8 中不起作用(如果需要,将提供)
回答by alecxe
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" elementand see if it is the desired one:
在浏览器中选择文本后,带有所选文本的元素的 CSS 样式不会改变。您可以做的是获取当前的“活动”元素并查看它是否是所需的元素:
WebElement desiredElement = driver.findElement(By.xpath("//*[@id='pageFooter']/div[3]/div/span"));
WebElement activeElement = driver.switchTo().activeElement();