无法定位元素:org.openqa.selenium.NoSuchElementException
Unable to locate element: org.openqa.selenium.NoSuchElementException
我正在编写一次性密码 (OTP) 手机号码验证脚本。当 OTP 弹出窗口打开时,我无法在文本字段中输入值,系统显示错误:
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();
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 等同于此。
或者,您可以使用该元素独有的不同定位器。
You need to correct your Xpath for "OTP text field" as below.
driver.findElement(By.xpath("//*[@id='verifyOTP_register']//*[@id='otp']")).sendKeys("1212121212");
此外,您可以使用 'relative' xpath 作为提交按钮,而不是使用 'absolute' xpath。
driver.findElement(By.xpath("//*[@id='verifyOTP_register']//*[@type='submit']")).click();
我正在编写一次性密码 (OTP) 手机号码验证脚本。当 OTP 弹出窗口打开时,我无法在文本字段中输入值,系统显示错误:
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();
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 等同于此。 或者,您可以使用该元素独有的不同定位器。
You need to correct your Xpath for "OTP text field" as below.
driver.findElement(By.xpath("//*[@id='verifyOTP_register']//*[@id='otp']")).sendKeys("1212121212");
此外,您可以使用 'relative' xpath 作为提交按钮,而不是使用 'absolute' xpath。
driver.findElement(By.xpath("//*[@id='verifyOTP_register']//*[@type='submit']")).click();