我正在学习《Web Scraping with Java》一书中有关网页抓取的教程。下面的代码给了我一个 nullPointerExcpetion。部分问题在于 (line = in.readLine())
始终为 null,因此第 33 行的 while 循环永远不会运行。但我不知道为什么它总是为空。谁能给我提供对此的见解?此代码应打印有关 CPython 的维基百科文章的第一段。
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.net.*;
import java.io.*;
public class WikiScraper {
public static void main(String[] args) {
scrapeTopic("/wiki/CPython");
}
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 an error connecting to the URL");
return "";
}
return outputText;
}
}
最佳答案
如果您输入http://www.wikipedia.org//wiki/CPython在网络浏览器中,它将被重定向到 https://en.wikipedia.org/wiki/CPython ,所以
使用String html = getUrl("https://en.wikipedia.org/"+url);
而是String html = getUrl("http://www.wikipedia.org/"+url);
那么line = in.readLine()
就可以真正读取一些东西了。
关于java - URL 连接上的 InputStreamReader 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48332886/