Find the all pdf's from webiste -error Exception in thread "main" java.lang.NullPointerException

28 views
Skip to first unread message

Santosh Awalekar

unread,
Jun 7, 2017, 4:25:22 AM6/7/17
to Selenium Users
package santosh_05_06_2017;
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.net.MalformedURLException;  
import java.net.URL;  
//import java.util.ArrayList;  
//import java.util.ArrayList;
import java.util.List;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.WebElement;  
import org.openqa.selenium.chrome.ChromeDriver;
//import org.openqa.selenium.htmlunit.HtmlUnitDriver; 
public class allpdf {

public static void main(String[] args) throws MalformedURLException, IOException {  
// List<WebElement>  uniqurl = new ArrayList();  
  
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
WebDriver driver= new ChromeDriver();
   driver.navigate().to("http://google.com/"); 
// get all page urls  
List<WebElement>  pdfurllist = driver.findElements(By.tagName("a"));  
  
for (WebElement elemnet : pdfurllist) {  
String pdfurl = elemnet.getAttribute("href").trim();  
//check pdf url  
if (pdfurl.contains(".pdf")) {  
// check one file download one time  
//if (!(uniqurl.contains(pdfurl))) {  
// uniqurl.add(pdfurl);  
//print file name and download url  
System.out.println(filename(pdfurl) + " ---&gt; " + pdfurl);  
//download file  
URL url = new URL(pdfurl);  
InputStream in = new BufferedInputStream(url.openStream());  
OutputStream out = new BufferedOutputStream(new FileOutputStream(filename(pdfurl)));  
  
for (int i; (i = in.read()) != -1;) {  
out.write(i);  
}  
in.close();  
out.close();  
            
 }  
 }  
}  
  
// close driver   
 
  
  
  
  // get file name. It depend on download url pattent.  
  private static String filename(String url) 
  {  
    String filename = "";  
    String file[];  
  
    file = url.split("\\/");  
    if (file[file.length - 1].contains("-")) 
    {  
      filename = file[file.length - 1].trim().replace("-", " ");  
    }
    else if (file[file.length - 1].contains("%20")) {  
      filename = file[file.length - 1].trim().replace("%20", " ");  
    }
    else
    {  
      filename = file[file.length - 1].trim();  
    }  
  
    return filename;  
  }  
  
 
}


thi...@thoughtworks.com

unread,
Jun 9, 2017, 1:42:44 AM6/9/17
to Selenium Users
Which line of code is throwing null pointer exception?
Reply all
Reply to author
Forward
0 new messages