2017-04-25 138 views
-1

Xpath昨天工作正常,我想點擊一個按鈕。但它今天不工作。當試圖運行腳本時,NoSuchElementException即將到來。下面我添加了代碼和錯誤。Xpath昨天是完美的工作,但今天它不工作

HTML代碼:

//Clicking on 'Add Customer' button 

driver.findElement(By.xpath(".//*[@id='userform']/section[1]/div/div[2]/input")).click(); 
Thread.sleep(5000); 

錯誤:

的 '添加用戶' 按鈕

<section class="content-header"> 
<div class="row"> 
<div class="col-xs-6"> 
<div class="col-xs-6 text-right"> 

<a class="btn btn-danger hidden checkdelbtn" data-content="Are you sure to continue?" data-title="Confirm" data-cancel="Cancel" data-confirm="Delete" data-form="userform" href=""> 

<input class="btn btn-primary" type="button" onclick="window.location.href='http://lab-1.sketchdemos.com/musicshop/stores/musicshop/admin/add-customer.html'" value="Add Customer"/> 

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

試過代碼

的源代碼

執行上面的代碼後,得到這個錯誤。

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[@id='userform']/section[1]/div/div[2]/input"}

Command duration or timeout: 32 milliseconds For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html Build info: version: '2.46.0', revision: '87c69e2', enter code here time: '2015-06-04 16:17:10' System info: host: 'SKETCH_QA-02', ip: '10.70.1.32', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_20' Driver info: org.openqa.selenium.firefox.FirefoxDriver

+0

這是因爲你的XPath是可怕試試下面這code。在這裏提出這樣的問題之前,你應該多瞭解一下它。 – acikojevic

回答

2

使用xpath locator

driver.findElement(By.xpath("//input[@value='Add Customer']")).click(); 

的XPath的說明試試這個下面code: -使用value<input>標籤的屬性。

注意: -而不是使用absolute xpath,請使用relative xpath

OR

使用cssSelector

driver.findElement(By.cssSelector("input[value='Add Customer']")).click(); 
+0

你有試過這個代碼嗎? –

+0

嗨耆那教,謝謝你的回答。我已經通過添加driver.manage()。timeouts()來解決這個問題了。implicitlyWait(10,TimeUnit.SECONDS);之前的代碼。現在它工作正常:) –

+0

請'接受'這個答案,所以它會幫助其他用戶以及:)並且你不明白我的觀點,你已經輸入了絕對路徑,這不是很好的做法。因爲一旦你的html會被修改,你會得到一個像'element not found'這樣的錯誤,所以你最好使用相對xpath。 –

相關問題