2013-12-14 10 views
11

Come ottengo un valore da href?get href value (WebDriver)

come questo esempio:

<div id="cont"><div class="bclass1" id="idOne">Test</div> 

    <div id="testId"><a href="**NEED THIS VALUE AS STRING**"> 
    <img src="img1.png" class="clasOne" /> 
    </a> 

</div> 
</div> 
</div> 

Ho bisogno che il valore come stringa.

Ho provato con questo:

String e = driverCE.findElement(By.xpath("//div[@id='testId']")).getAttribute("href"); 
      JOptionPane.showMessageDialog(null, e); 

Ma solo restituisce il valore NULL ...

risposta

33

Si hanno sottolineato il vostro elemento a 'div' invece di 'un'

provare il sotto il codice

+0

Ora funziona! Grazie. – user3062055

+5

@ user3062055 Non dimenticare di contrassegnare questa risposta come accettata. – Stephan

0

Se si dispone di più di un tag di ancoraggio, il seguente frammento di codice aiuterà per trovare tutti i link indicati da href

//find all anchor tags in the page 
List<WebElement> refList = driver.findElements(By.tagName("a")); 

    //iterate over web elements and use the getAttribute method to 
    //find the hypertext reference's value. 

    for(WebElement we : refList) { 
     System.out.println(we.getAttribute("href")); 
    }