我使用的是Java Eclipse和导入的jsoup包,以便从Amazon网站上抓取。程序只是转到一个搜索页面,查看结果的数量,如果有任何变化,就会在屏幕的左侧发出通知,并不断地用计时器重新加载页面。它工作得很好,过了一段时间后,它不断地显示错误。有时它会正确执行。
我尝试使用if(select=!null),但结果为空。这意味着选择器有时会抓取数据,有时会得到空值。
package main;
import java.awt.AWTException;
import java.awt.SystemTray;
import java.io.IOException;
import java.net.MalformedURLException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.Timer;
import java.util.TimerTask;
class amazon1 extends TimerTask{
public static int result1;
public static int result2;
public static int result3;
public void run() {
try {
final Document doc =
Jsoup.connect("http://www.amazon.com/s?k=hello&i=stripbooks-intl-
ship&ref=nb_sb_noss")
.userAgent("Mozilla/17.0")
.get()
;
Elements select = doc.select("div.a-section.a-spacing-
small.a-spacing-top-small>span");
Element first = select.first();
String contentText = first.text();
amazon1.result1 =
Integer.parseInt(contentText.replaceAll("[\\D]",""));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
if(amazon1.result1>amazon1.result2) {
System.out.println(amazon1.result1);
amazon1.result2 = amazon1.result1;
amazon1.result3 = amazon1.result1 - amazon1.result2;
if (SystemTray.isSupported()) {
DisplayTrayIcon td = new DisplayTrayIcon();
try {
td.displayTray();
} catch (MalformedURLException | AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.err.println("System tray not supported!");
}
} else {
;
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
Timer timer = new Timer();
TimerTask task = new amazon1();
timer.schedule(task, 3000, 5000);
}
}
错误是..
Exception in thread "Timer-0" java.lang.NullPointerException
at main.amazon1.run(Main.java:31)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
NullPointer异常来自于选择类元素。输出应为11620000,并从屏幕右侧通知。
发布于 2019-05-21 11:18:48
Samuel Philipp认为这个问题指的是Stackoverflow (What is a NullPointerException, and how do I fix it?)上的经典问题“什么是NullPointerExcelption”,这是没有错的。
但是,由于您只会偶尔遇到NullPointerException,因此值得考虑发生这种情况的原因。
我的猜测如下所示。有时,你试图访问的网站不可用,或者它阻止了你的请求,例如,如果你重复太多次。在这种情况下,这行
final Document doc = Jsoup.connect(
"http://www.amazon.com/s?k=hello&i=stripbooksintl-ship&ref=nb_sb_noss")
.userAgent("Mozilla/17.0")
.get();
都会以doc == null
收尾。这就是select方法失败并出现异常的原因。
要解决这个问题,可以终止catch (IOException e)
块,或者在connect
方法之后检查doc是否为空。
} catch (IOException e) {
// it seems the website is not reachable or the content is not according to the expectations.
System.err.println("website not reachable or content malformed");
// you may need to set the result1, result2, result3 variables accordingly here
amazon1.rsult1 = 0;
amazon1.rsult2 = 0;
amazon1.rsult3 = 0;
return;
}
https://stackoverflow.com/questions/56226652
复制相似问题