2015-07-20 61 views
0

下面是代碼:我如何點擊Selenium中的這個href鏈接?

<div class="padding"> 
     <a href="javascript:FreshCoShowEFlyerOverlay()"> 
      <img alt="Example" src="http://freshco.wpengine.com/wp-content/uploads/2015/05/week-flyer-left.jpg" height="158" width="280"> 
     </a> 
</div> 

我想點擊的href。我曾經試過,但它不工作:

driver.findElement(By.xpath("//href[text()='javascript:FreshCoShowEFlyerOverlay']")).click(); 
+0

你這是什麼意思是_it不工作_?你有錯誤嗎?什麼都沒有發生? – Keppil

+0

'href'不是標籤,而是屬性。 –

+0

它拋出org.openqa.selenium.NoSuchElementException –

回答

2

使用此:

driver.findElement(By.xpath("//a[@href='javascript:FreshCoShowEFlyerOverlay']")).click(); 

這一翻譯的:

driver.findElement(By.xpath("//href[text()='javascript:FreshCoShowEFlyerOverlay']")).click(); 
+0

這給了我這個錯誤:線程「main」中的異常org.openqa.selenium.NoSuchElementException:無法找到元素:{「method」:「xpath」,「selector」:「 // a [@ href ='javascript:FreshCoShowEFlyerOverlay']「} –

+0

可能你可能有一個具有相同href的元素。你可以發佈這個Html代碼的父標籤嗎? –

+0

// img [@ alt ='示例']。一旦嘗試這一點。 –

0

作爲另一種變體:

driver.findElement(By.CssSelector("a[href*='FreshCoShowEFlyerOverlay']")).click();