单击按钮后,我将尝试获取主体元素的背景色和按钮元素的文本颜色。
<html>
<head>
<style>
#container
{
width: 100px;
height: 100px;
border: 1px solid #ccc;
overflow-x: scroll;
}
#content
{
margin:4px, 4px;
padding:4px;
width: 500px;
height:500px;
text-align:justify;
background-color: #ccc;
}
</style>
</head>
<body>
<div id="container">
<div id="content">Click the button to slide right!</div>
</div>
<button id="slide" type="button" onclick="dem_func()">Slide right</button>
<script>
function dem_func()
{
document.getElementById('container').scrollLeft += 50;
<!-- Changing the text color of button element-->
document.getElementById('slide').style.color='red'
<!-- Changing the background color of body element-->
document.body.style.backgroundColor='yellow'
return document.getElementById('slide').style.color
}
</script>
</body>
</html>HTML代码的工作:单击按钮后,页面正文的背景色变为黄色,按钮的文本颜色按照Javascript函数更改为红色。此外,样式属性被内联地追加到DOM中的body和按钮元素,如下所示:
<body style="background-color: yellow;">
<div id="container">
<div id="content">Click the button to slide right!</div>
</div>
<button id="slide" type="button" onclick="dem_func()" style="color: red;">Slide right</button>String color1 = driver.findElement(By.xpath("child::html/child::body")).getAttribute("background-color");
System.out.println("Color of the background of body element: " + color1);
String color2 = driver.findElement(By.xpath("//button")).getAttribute("color");
System.out.println("Color of the text of button element: " + color2);根据Selenium for getAttribute()方法:
获取元素的给定属性的值。将返回当前值,即使在加载页面后对此进行了修改。更确切地说,如果存在该方法,则该方法将返回具有给定名称的属性的值。如果没有,则返回具有给定名称的属性的值。如果不存在,则返回null。
但是在这里,它对color1和color2都返回null。
我想了解为什么getAttribute方法返回null。
发布于 2020-09-16 09:36:44
您应该获得CSS值而不是attribute.Below示例代码将在单击之前和之后打印背景颜色。
WebElement.getCssValue("cssproperty")将返回元素的相应css属性。
WebElement body=driver.findElement(By.tagName("body"));
WebElement button=driver.findElement(By.id("slide"));
System.out.println("Body bg-color Before Click: "+body.getCssValue("background-color"));
System.out.println("Button bg-color Before Click: "+button.getCssValue("color"));
System.out.println();
button.click();
System.out.println("Body bg-color After Click: "+body.getCssValue("background-color"));
System.out.println("Button bg-color After Click: "+button.getCssValue("color"));https://sqa.stackexchange.com/questions/45760
复制相似问题