【问题标题】:Java/selenium Nullpointer exception for FileOutputStreamFileOutputStream 的 Java/selenium Nullpointer 异常
【发布时间】:2021-02-21 23:22:57
【问题描述】:

我正在尝试从 Internet 获取一些数据,然后将其保存在一个 txt 文件中,但我得到一个 Nullpointer 异常,内容如下: 信息:检测到的方言:W3C mypackage.testClass.main(testClass.java:31) 处的线程“main”java.lang.NullPointerException 中的异常。 所以,它实际上将我引向这一行:byte[] contentInBytes = aaa.getBytes();

代码如下:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.*;



public class testClass {

    public static void main(String[] args) {
        System.setProperty("webdriver.gecko.driver","chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.blablawebsite.com/path");
        List<WebElement> urls = driver.findElements(By.xpath("//li[contains(@text(),'text')]"));
        int i;
        
        try {
            File file = new File("/path/to/file/text.txt");
            FileOutputStream fos = new FileOutputStream(file); 
            if(!file.exists()) 
                file.createNewFile();
            
                for(i=0; i <urls.size(); i++) { 
                    String aaa = urls.get(i).getAttribute("data-asin");
                    byte[] contentInBytes = aaa.getBytes();
                    fos.write(contentInBytes);
                    fos.flush();
                    fos.close();
            
            }
                
                
            
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        
        
    }

}

【问题讨论】:

  • 所以我猜String aaa = urls.get(i).getAttribute("data-asin");这个属性是不存在的。

标签: java selenium nullpointerexception fileoutputstream


【解决方案1】:

这不是一个具体的解决方案,而是一个寻找答案的建议。

为了找出您收到 NullPointerException 的时间和原因,您可以暂时打印 aaa

System.out.println("i = " + i + " -> aaa = " + aaa);

aaa 初始化之后添加该行。然后,您可以应用所需的逻辑来处理该场景。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多