【问题标题】:Read PDF in selenium: The constructor PDFParser(BufferedInputStream) is undefined在 selenium 中读取 PDF:构造函数 PDFParser(BufferedInputStream) 未定义
【发布时间】:2016-08-30 17:22:01
【问题描述】:

我遇到错误

构造函数 PDFParser(BufferedInputStream) 未定义

我正在尝试使用 Selenium 阅读 PDF 内容。

WebDriver driver=new FirefoxDriver();
driver.get("http://www.axmag.com/download/pdfurl-guide.pdf");
URL TestURL = new URL("http://www.axmag.com/download/pdfurl-guide.pdf");
BufferedInputStream TestFile = new BufferedInputStream(TestURL.openStream());
PDFParser TestPDF = new PDFParser(TestFile);
TestPDF.parse();
String TestText = new PDFTextStripper().getText(TestPDF.getPDDocument());
System.out.println(TestText);
Assert.assertTrue(TestText.contains("Open the setting.xml, you can see it is like this"));

有人可以帮忙吗?

【问题讨论】:

    标签: selenium pdf selenium-webdriver testng pdfbox


    【解决方案1】:

    PDFBox 2.0.2(也适用于 1.8.*)的最佳代码是这样的 - 您只需调用 PDDocument.load() 即可打开 PDF 文件:

    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.axmag.com/download/pdfurl-guide.pdf");
    URL url = new URL("http://www.axmag.com/download/pdfurl-guide.pdf");
    BufferedInputStream bis = new BufferedInputStream(url.openStream());
    PDDocument doc = PDDocument.load(bis);
    String text = new PDFTextStripper().getText(doc);
    doc.close();
    bis.close();
    System.out.println(text);
    Assert.assertTrue(text.contains("Open the setting.xml, you can see it is like this"));
    

    【讨论】:

    • PDDocument doc = PDDocument.load(bis); seleniumeasy.com/selenium-tutorials/… 这应该是公认的答案,因为另一行要求您恢复到旧版本的 PDFBox,这不是一个好主意,原因有很多.
    • 是提出问题的人决定接受的答案是什么。有时,接受的答案比另一个答案得票少?
    【解决方案2】:

    我遇到了与您相同的问题。问题是由于使用(Apache PDFBox 2.0.0 API)jar 文件。 从构建路径中删除它们并使用(Apache PDFBox 1.8.11 API),因为 2.0 中的 PDFParser 类没有 PDFParser(BufferedInputStream args) 构造函数。但是 1.8 有 PDFParser(InputStream args) 构造函数。所以它一定会解决你的问题。

    我也会分享我的代码。如果您需要帮助,您可以从中获得帮助。

    InputStream is = new FileInputStream(getLatestFile);
            PDFParser parser = new PDFParser(is);
            parser.parse();
            String output=new PDFTextStripper().getText(parser.getPDDocument());
            System.out.println(output);
            parser.getPDDocument().close(); 
    

    【讨论】:

    • 可能有效,您使用的是过时的打开文件方法。 (可以在几个 SEO 网站上找到)
    • 下面的评论解决了问题,而无需恢复到旧版本的库。我建议使用该解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 2020-09-30
    相关资源
    最近更新 更多