2014-11-22 20 views
1

下面是我试过的这个脚本。如何使用Xpath获取CSS颜色值?

  1. 如何使用此XPath识别元素并获取CSS颜色值?
  2. 这个Xpath是什么意思?

    package mypackage;  
    import org.openqa.selenium.*; 
    import org.openqa.selenium.firefox.FirefoxDriver;  
    import org.openqa.selenium.interactions.Action; 
    import org.openqa.selenium.interactions.Actions; 
    
    public class myclass { 
    
         public static void main(String[] args) { 
         String baseUrl = "http://newtours.demoaut.com/"; 
         WebDriver driver = new FirefoxDriver(); 
    
         driver.get(baseUrl); 
         WebElement link_Home = driver.findElement(By.linkText("Home")); 
         WebElement td_Home = driver 
         .findElement(By 
         .xpath("//html/body/div" 
         + "/table/tbody/tr/td" 
         + "/table/tbody/tr/td" 
         + "/table/tbody/tr/td" 
         + "/table/tbody/tr")); 
    
         Actions builder = new Actions(driver); 
         Action mouseOverHome = builder 
         .moveToElement(link_Home) 
         .build(); 
    
         String bgColor = td_Home.getCssValue("background-color"); 
         System.out.println("Before hover: " + bgColor); 
         mouseOverHome.perform(); 
         bgColor = td_Home.getCssValue("background-color"); 
         System.out.println("After hover: " + bgColor); 
         driver.quit(); 
        } 
    } 
    
+0

你能更具体地请问你到底想知道什么?因为,简单的谷歌搜索会告诉你所有关于xpath的信息。 – Subh 2014-11-22 11:40:23

回答

1

要获得使用XPath CSS颜色值,你可以使用此代码:

String color = driver.findElement(By.xpath("//xpath")).getCssValue("color"); 

它将在 “RGBA” 格式返回输出为:“RGBA(255,255, 255,1)“。

0

首先,这当然不是编写xpath的有效方法。我测试了你的xpath,它返回了9个不同的比赛。要找到css特定元素的颜色值,您的xpath或任何其他选择器需要非常具体。之后,getCssValue和任何有效的财产名称,如color, background-color等将返回您的愿望值。除了选择器,你的代码对我来说看起来很好。此外,如果您想查找所有元素的css值,您可能想要循环并打印每个元素的值。 enter image description here