2014-02-11 32 views
22

<div class="value test" /> 我想確定那個web元素。它只有這兩個類定義。 由於className沒有使用空格分隔的值,因此我無法執行以下操作。什麼是替代品?通過多個類名查找div元素?

@FindBy(className = "value test") 
@CacheLookup 
private WebElement test; 

回答

54

我不認爲巴拉克馬諾斯的回答充分說明它。

試想一下,我們有幾個元素情況如下:

  1. <div class="value test"></div>
  2. <div class="value test "></div>
  3. <div class="first value test last"></div>
  4. <div class="test value"></div>

的XPath如何匹配

  • 比賽只有1(精確匹配),巴拉克的回答

    driver.findElement(By.xpath("//div[@class='value test']")); 
    
  • 比賽1,2和3(匹配類包含value test,一流的秩序事項)

    driver.findElement(By.xpath("//div[contains(@class, 'value test')]")); 
    
  • 1場, 2,3和4(只要元素具有類別valuetest

    driver.findElement(By.xpath("//div[contains(@class, 'value') and contains(@class, 'test')]")); 
    

此外,在這種情況下,Css Selector始終支持XPath(快速,簡潔,本機)。

  • 匹配1

    driver.findElement(By.cssSelector("div[class='value test']")); 
    
  • 第1場,第2和3

    driver.findElement(By.cssSelector("div[class*='value test']")); 
    
  • 匹配1,2,3和4

    driver.findElement(By.cssSelector("div.value.test")); 
    
5

試試這個:

test = driver.findElement(By.xpath("//div[@class='value test']"));