2013-12-14 3 views
11

hrefから値を取得するにはどうすればよいですか?この例のようにhref値を取得する(WebDriver)

<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> 

私は文字列としてその値を必要とします。

私はこれを試してみた

:あなたは ''

お試しください。代わりに 'DIV' にあなたの要素を指摘している

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

しかし、単にはNULL値を返します...

答えて

33

コードの下に

driverCE.findElement(By.xpath("//div[@id='testId']/a")).getAttribute("href"); 
+0

現在作業中です!ありがとう。 – user3062055

+5

@ user3062055この回答を承認済みとマークすることを忘れないでください。 – Stephan

0

複数のアンカータグがある場合は、次のコードスニペットが役立ちます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")); 
    }