我正在字符串中发送用户名和密码字段中的登录凭据https://www.vignanits.ac.in/server/moodle/login/index.php需要使用HtmlUnitDriver进行自动化,但面临NoSuchElementException。
代码试用:
package leela;
import org.openqa.selenium.By;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import com.gargoylesoftware.htmlunit.WebClient;
public class LeelaHtmlUnit {
public static void main(String[] args) throws InterruptedException {
HtmlUnitDriver driver = new HtmlUnitDriver(true);
driver.get("https://www.vignanits.ac.in/server/moodle/login/index.php");
System.out.println(driver.getCurrentUrl()+driver.getTitle());
driver.findElement(By.id("username")).sendKeys("xyz");
driver.findElement(By.id("password")).sendKeys("xyz");
driver.findElement(By.id("loginbtn")).click();
System.out.println(driver.getCurrentUrl()+driver.getTitle());
}
}
理想情况下,要使用htmlunit驱动程序,您需要下载htmlunit-driver-2.42.0-jar-with-dependences.jar最新版本。
下面的代码块在我的端完美工作:
import org.openqa.selenium.By;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class HtmlUnitDriverDemo {
public static void main(String[] args) {
HtmlUnitDriver driver = new HtmlUnitDriver();
driver.get("https://www.vignanits.ac.in/server/moodle/login/index.php");
System.out.println(driver.getCurrentUrl()+driver.getTitle());
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("username")));
driver.findElement(By.id("password")).sendKeys("xyz");
driver.findElement(By.id("loginbtn")).click();
}
}
控制台输出:
https://www.vignanits.ac.in/server/moodle/login/index.phpVIGNAN MOODLE: Log in to the site
参考
您可以在以下位置找到关于NoSuchElementException的详细讨论:
- NoSuchElementException,Selenium无法定位元素