selenium - Selenium WebDriver 中的空指针异常

标签 selenium

我正在使用下面的代码通过使用 WebDriver 逐一单击导航链接,直到到达末尾,但它抛出 NullPointerException,因为我已经初始化并且仍然面临这个问题,所以很困惑,请帮助。

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class Exercise_dice {
    static WebDriver driver;
    public static void main(String[] args) {
        WebDriver driver=new FirefoxDriver();
        driver.get("http://www.dice.com");
        driver.findElement(By.xpath("//*[@id='FREE_TEXT']")).sendKeys("selenium");
        driver.findElement(By.xpath("//*[@id='searchSubmit']")).click();

        String part1= "//*[@id='yui-main']/div/div[1]/div[1]/div[1]/a[";
        String part2= "]";

        int i=1;
        while(isElementPresent(part1+i+part2)){
            String text= driver.findElement(By.xpath(part1+i+part2)).getText();
            System.out.println(text);
            driver.findElement(By.xpath(part1+i+part2)).click();
            i++;
        }
    }

    public static boolean isElementPresent(String element_xpath){
        int count=driver.findElements(By.xpath(element_xpath)).size();

        if (count == 0)
            return false;
        else 
            return true;
    }
}

最佳答案

我相信你的问题从这里开始:

static WebDriver driver;
public static void main(String[] args) {
    WebDriver driver=new FirefoxDriver();

您已声明 driver 两次。然后,您在 isElementPresent 中使用未初始化的driver

我认为您可以按如下方式解决此问题:

static WebDriver driver;
public static void main(String[] args) {
    driver=new FirefoxDriver();

关于selenium - Selenium WebDriver 中的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23123963/

相关文章:

javascript - Capybara/Selenium 在 location.reload() 上随机获取一个 Net::ReadTimeout

java - 如何根据给定的 HTML 单击单选按钮

java - 如何使用ios应用程序不同元素的属性创建xpath

java - 使用 Selenium + Java 选择网页上的所有复选框时出现问题

java - 线程中的异常 "main"java.lang.IllegalStateException :The path to the driver executable must be set by the : system property

selenium - org.openqa.selenium.remote.UnreachableBrowserException : Error communicating with the remote browser. 它可能与 ChromeDriver 和 Selenium 一起死亡

java - 如何传递 Jenkins 配置来覆盖自动化配置

Selenium Webdriver 无法获取 Modal 中的元素

selenium - 如何开始使用 Selenium 2?

java - Selenium Standalone 已退出,代码为 1/系统找不到指定的路径