首先,我是Spring Boot的新手。我想报废新闻网站以制作一个api。
我所做的只是创建一条路由,负责在抓取新闻网站后为最新新闻创建json响应。
这是路线
@GetMapping("/latest")
public ArrayList<Result> scrap() {
String title = "";
Document doc;
Element body ;
ArrayList<Element> elements = new ArrayList<>() ;
ArrayList<Result> results = new ArrayList<>();
ArrayList<Element>li;
try {
doc = Jsoup.connect("https://timesofindia.indiatimes.com").get(); //error take place here
title = doc.title();
body = doc.body();
elements = body.getElementsByAttributeValue("data-vr-zone","latest");
System.out.println("Size "+elements.size());
li = elements.get(0).select("li > a");
System.out.println("WHole Data "+li.toString());
System.out.println(li.size());
int id = 0;
for(Element text : li ) {
id++;
String link = "";
if( text.attr("href") != "" && text.attr("title") != "" ) {
link = "https://timesofindia.indiatimes.com/" + text.attr("href") ;
results.add(new Result(id,text.attr("title"),link));
}
}
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
请有人帮助如何处理Java中的这种情况。
因为
Jsoup.connect().get()
发出了http
请求,所以主线程将其放在一个唯一的线程中以并行执行,并输出ArrayList = 0的大小。Here is the Output
堆栈跟踪:
2020-03-04T12:18:34.410009+00:00 heroku[router]: at=info method=GET path="/latest" host=morning-waters-01018.herokuapp.com request_id=15a8fdba-e541-4aa2-a0df-34838b2e7e5f fwd="47.30.171.180" dyno=web.1 connect=0ms service=177ms status=500 bytes=473 protocol=https 2020-03-04T12:18:34.399950+00:00 app[web.1]: Size 0 2020-03-04T12:18:34.402793+00:00 app[web.1]: 2020-03-04 12:18:34.402 ERROR 4 --- [io-17255-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IndexOutOfBoundsException: Index: 0, Size: 0] with root cause 2020-03-04T12:18:34.402794+00:00 app[web.1]: 2020-03-04T12:18:34.402795+00:00 app[web.1]: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 2020-03-04T12:18:34.402796+00:00 app[web.1]: at java.util.ArrayList.rangeCheck(ArrayList.java:657) ~[na:1.8.0_242-heroku] 2020-03-04T12:18:34.402797+00:00 app[web.1]: at java.util.ArrayList.get(ArrayList.java:433) ~[na:1.8.0_242-heroku]
最佳答案
我认为Jsoup.connect("https://timesofindia.indiatimes.com").get()
可以进行同步调用。
您只需要找到错误的原因。
最简单的方法
请将catch (IOException e)
更改为catch (Exception e)
。
将main()
方法添加到同一源文件,在scrap()
中复制main()
的主体,然后在IDE中运行main()
方法。您可以只打印results
(不返回它们)。
您可以尝试在main()
方法中调试代码。
原因,看起来像elements = body.getElementsByAttributeValue("data-vr-zone","latest")
elements
在这里是空的
关于java - 如何防止主线程执行下一行,直到最后一行完全执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60525753/