首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Selenium getAttribute(“背景颜色”)和getAttribute(“颜色”)返回空。

Selenium getAttribute(“背景颜色”)和getAttribute(“颜色”)返回空。
EN

Stack Exchange QA用户
提问于 2020-09-16 08:47:23
回答 1查看 3.4K关注 0票数 1

单击按钮后,我将尝试获取主体元素的背景色和按钮元素的文本颜色。

HTML代码:

代码语言:javascript
运行
复制
<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和按钮元素,如下所示:

代码语言:javascript
运行
复制
<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>

Selenium代码:

代码语言:javascript
运行
复制
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。

EN

回答 1

Stack Exchange QA用户

回答已采纳

发布于 2020-09-16 09:36:44

您应该获得CSS值而不是attribute.Below示例代码将在单击之前和之后打印背景颜色。

WebElement.getCssValue("cssproperty")将返回元素的相应css属性。

代码语言:javascript
运行
复制
    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"));
票数 3
EN
页面原文内容由Stack Exchange QA提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://sqa.stackexchange.com/questions/45760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档