java - 无法使用 Selenium(java) 从网站获取错误消息并在 Eclipse 控制台中打印
问题描述
我正在尝试在 SalesForce 网站上打印错误消息以输入错误的用户名和密码
package today;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Gmail {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\selenium\\chromedriver.exe"); WebDriver mail=new ChromeDriver();
mail.get("https://login.salesforce.com/?locale=in");
mail.findElement(By.cssSelector("#username")).sendKeys("judinkp@gmail.com");
mail.findElement(By.xpath("//*[@id=\"password\"]")).sendKeys("23232");
mail.findElement(By.id("Login")).click();
System.out.println(mail.findElement(By.xpath("//*[@id='error']")).getText());
}
}
我的脚本一直运行,直到它点击,Login
但网站中打印的错误消息没有在我的控制台中打印,我收到以下错误消息
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@class='loginError']"}
(Session info: chrome=80.0.3987.149)
Xpath 是浏览器给定的 Xpath。
网站链接:https: //login.salesforce.com/?locale=in
解决方案
您能否尝试以下解决方案:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginScreen {
public static void main(String[] args) {
System.out.println("launching chrome browser");
System.setProperty("webdriver.chrome.driver", "C:\\selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("https://login.salesforce.com/?locale=in");
driver.get("https://login.salesforce.com/?locale=in");
driver.findElement(By.cssSelector("#username")).sendKeys("judinkp@gmail.com");
driver.findElement(By.id("password")).sendKeys("23232");
driver.findElement(By.id("Login")).click();
WebDriverWait wait = new WebDriverWait(driver,20);
WebElement error= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("error")));
System.out.println(error.getText());
}
}
推荐阅读
- javascript - 使用 CJS 和 ESM 模块是否存在兼容性问题?
- authentication - 如何在一个应用程序中进行多用户登录?
- regex - 如何用“sed”或“awk”替换每行中第二次出现的空格?
- c++ - 如何将一个函数中的值用于主函数?
- linux - 如何在 ubuntu 18.04 上临时和永久打开/关闭 kaslr?
- image - 在数据集类上使用自定义函数调用 DataLoader 时的执行块
- javascript - 如何将上传的文件显示为附件,而不是以角度显示整个 url
- javascript - 如何在 express().use 中调用一个类?
- prolog - 序言中缺席事实的否定
- android - 在 Flutter 中制作自定义小部件时 onPress 不起作用