2016-04-23 141 views
0

我正在通過一次性密碼(OTP)編寫用於手機號碼驗證的腳本。雖然OTP彈出是開放的,我不能把值在文本字段中,系統顯示錯誤:無法找到元素:org.openqa.selenium.NoSuchElementException

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"class name","selector":"opt_success"} Command duration or timeout: 30.04 seconds"

下面是我起草的代碼。

driver.findElement(By.id("phone")).sendKeys(Constants.MOBILE_NUMBER); 
     driver.findElement(By.id("btn_verify")).click(); 
     driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
     WebElement otp_value = driver.findElement(By.id("otp")); 
     otp_value.sendKeys("1212121212"); 
     driver.findElement(By.xpath("html/body/div[4]/div/form/div/div[4]/span[1]/input")).click(); 

網頁的網址是:http://talentrack.in/register

+2

錯誤不是來自您的代碼有問題。你能告訴我們調用'findElement(by.className(「opt_success」))''的行嗎? – Buaban

+0

Buaban是對的。您顯示的代碼不會導致您顯示的錯誤。有更多的代碼,顯示它。謝謝。 – alecxe

回答

0

You need to correct your Xpath for "OTP text field" as below.

driver.findElement(By.xpath("//*[@id='verifyOTP_register']//*[@id='otp']")).sendKeys("1212121212"); 

此外,您還可以使用 '相對' 的XPath提交的,而不是用 '絕對' 的XPath按鈕。

driver.findElement(By.xpath("//*[@id='verifyOTP_register']//*[@type='submit']")).click(); 
+0

真的有用,它工作正常!感謝Srikanth –

0
WebElement otp_value = driver.findElement(By.id("otp")); 

這這裏是你的問題。在頁面上有2個ID爲「otp」的元素。你找到第一個隱藏的,但你需要第二個。

您可以使用WebDriverWait來查找可見元素。我這樣做在Python像這樣:

element = WebDriverWait(driver, 0).until(EC.presence_of_element_located((By.ID, "otp"))) 
return element 

傳遞到WebDriverWait 0超時意味着它只會試圖找到該元素一次。你可以做一個方法來做到這一點,並傳遞一個超時參數以便重用。

我確定有這個Java的等價物。 或者,您可以使用元素所特有的不同定位器。

+1

'find_visible_element'?你確定在python-selenium中有這種方法嗎? :) – alecxe

+0

@alecxe你說得對,那是我自己創造的一種方法。我已經解決了答案,但我只注意到Buaban的評論說錯誤不是顯示的代碼,他是正確的。所以我想這不是正確的答案。 – RemcoW