【发布时间】:2021-07-05 12:02:33
【问题描述】:
这是我的 Java 代码:
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class FirstSeleniumTest {
public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\35196\\IdeaProjects\\selenium test\\SeleniumTest\\lib\\seleniumjars\\chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("https://foodplanhealth.herokuapp.com/login");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
WebElement root1 = driver.findElement(By.cssSelector("my-app"));
WebElement shadow_root1 = expand_shadow_element(root1);
WebElement root2 = shadow_root1.findElement(By.cssSelector("mwc-drawer"));
WebElement shadow_root2= expand_shadow_element(root2);
WebElement root3 = shadow_root2.findElement(By.name("appContent"));
WebElement shadow_root3 = expand_shadow_element(root3);
WebElement root4 = shadow_root3.findElement(By.tagName("div#main-content"));
WebElement shadow_root4 = expand_shadow_element(root4);
WebElement root5 = shadow_root4.findElement(By.cssSelector("div#container"));
WebElement shadow_root5 = expand_shadow_element(root5);
WebElement root6 = shadow_root5.findElement(By.cssSelector("login-container"));
WebElement shadow_root6 = expand_shadow_element(root6);
WebElement root7 = shadow_root6.findElement(By.cssSelector("mwc-textfield"));
WebElement shadow_root7 = expand_shadow_element(root7);
WebElement root8 = shadow_root7.findElement(By.cssSelector("mdc-text-field__ripple"));
WebElement shadow_root8 = expand_shadow_element(root8);
WebElement login = shadow_root8.findElement(By.cssSelector("mdc-text-field__input"));
String js = "arguments[0].setAttribute('value','random@email.com')";
((JavascriptExecutor) driver).executeScript(js, login);
}
public static WebElement expand_shadow_element(WebElement element)
{
return (WebElement)((JavascriptExecutor)driver).executeScript("return arguments[0].shadowRoot", element);
}
}
代码运行良好,直到第 35 行
WebElement root4 = shadow_root3.findElement(By.tagName("div#main-content"));
我在哪里得到这个错误
线程“main”中的异常 java.lang.NullPointerException at test.FirstSeleniumTest.main(FirstSeleniumTest.java:35)
我知道整个代码不正确且不完整,但由于此错误,我无法继续前进。我只是不明白为什么它在这一点上工作正常,但它没有。我向某人寻求帮助,他们告诉我代码对他们来说运行良好,我检查了 chrome 驱动程序版本,它与浏览器版本匹配。
谁能告诉我怎么回事?
【问题讨论】:
-
div#main-content是标签名吗?看起来像选择器 -
第 35 行的某些内容为 null,您不能在 null 对象上调用方法
标签: java selenium google-chrome selenium-chromedriver