我對網頁抓取相當陌生,對Java知識有限。運行網頁抓取程序時出現「線程異常」主「java.lang.NullPointerException」錯誤
我每次運行此代碼,我得到的錯誤:
Exception in thread "main" java.lang.NullPointerException
at sws.SWS.scrapeTopic(SWS.java:38)
at sws.SWS.main(SWS.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
我的代碼是:
import java.io.*;
import java.net.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class SWS
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
scrapeTopic("wiki/Python");
}
public static void scrapeTopic(String url)
{
String html = getUrl("http://www.wikipedia.org/" + url);
Document doc = Jsoup.parse(html);
String contentText = doc.select("#mw-content-text > p").first().text();
System.out.println(contentText);
}
public static String getUrl(String Url)
{
URL urlObj = null;
try
{
urlObj = new URL(Url);
}
catch(MalformedURLException e)
{
System.out.println("The url was malformed");
return "";
}
URLConnection urlCon = null;
BufferedReader in = null;
String outputText = "";
try
{
urlCon = urlObj.openConnection();
in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
String line = "";
while ((line = in.readLine()) != null)
{
outputText += line;
}
in.close();
}
catch(IOException e)
{
System.out.println("There was a problem connecting to the url");
return "";
}
return outputText;
}
}
我已經在我盯着屏幕的某個時候現在需要幫助的!
在此先感謝。
哪一行是'SWS.java:38'? – ssantos