如何修复HTTP错误提取URL。 在抓取时java中的状态= 500?

我试图从评论页面抓取用户对imdb影院电影的评级:(我数据库中的电影数量约为600,000)。 我使用jsoup解析页面如下:(对不起,我没有在这里写完整个代码,因为它太长了)

try { //connecting to mysql db ResultSet res = st .executeQuery("SELECT id, title, production_year " + "FROM title " + "WHERE kind_id =1 " + "LIMIT 0 , 100000"); while (res.next()){ ....... ....... String baseUrl = "http://www.imdb.com/search/title?release_date=" + ""+year+","+year+"&title="+movieName+"" + "&title_type=feature,short,documentary,unknown"; Document doc = Jsoup.connect(baseUrl) .userAgent("Mozilla") .timeout(0).get(); ..... ..... //insert ratings into database ... 

我测试了它的前100个,然后是前500个,也是我的数据库中的前2000个电影,它运行良好。 但问题是,当我测试了100,000部电影时,我收到了这个错误:

 org.jsoup.HttpStatusException: HTTP error fetching URL. Status=500, URL=http://www.imdb.com/search/title?release_date=1899,1899&title='Columbia'%20Close%20to%20the%20Wind&title_type=feature,short,documentary,unknown at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:449) at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:424) at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:178) at org.jsoup.helper.HttpConnection.get(HttpConnection.java:167) at imdb.main(imdb.java:47) 

我搜索了很多这个错误,我发现这是一个服务器端错误,错误号为5xx。

然后我决定设置一个条件,当连接失败时,它再尝试2次,然后如果仍然无法连接,则不会停止并转到下一个URL。 因为我是java新手,所以我试图搜索类似的问题,并在stackoverflow中阅读这些答案:

我从网站提取数据时的例外情况

当无法连接到网站时,Jsouperror handling

处理连接错误和JSoup

但是,当我按照他们的建议尝试使用“Connection.Response”时,它会告诉我“Connection.Response无法解析为某种类型”。

我很感激,如果有人可以帮助我,因为我只是一个新手,我知道它可能很简单,但我不知道如何解决它。


好吧,我可以通过添加“ignoreHttpError(true)”来修复http错误状态500,如下所示:

 org.jsoup.Connection con = Jsoup.connect(baseUrl).userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21"); con.timeout(180000).ignoreHttpErrors(true).followRedirects(true); Response resp = con.execute(); Document doc = null; if (resp.statusCode() == 200) { doc = con.get(); ...... 

希望它能帮助那些有同样错误的人。

然而,在抓取22907部电影(约12小时)的评论页面后,我又收到了一个错误:
“读取超时”。

我感谢任何修复此错误的建议。

将我的评论升级为答案:

Connection.Responseorg.jsoup.Connection.Response

要仅在有有效的http代码(200)时允许document实例,请将您的呼叫分成3部分; ConnectionResponseDocument

因此,您上面的代码部分被修改为:

 while (res.next()){ ....... ....... String baseUrl = "http://www.imdb.com/search/title?release_date=" + "" + year + "," + year + "&title=" + movieName + "" + "&title_type=feature,short,documentary,unknown"; Connection con = Jsoup.connect(baseUrl).userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21").timeout(10000); Connection.Response resp = con.execute(); Document doc = null; if (resp.statusCode() == 200) { doc = con.get(); .... } 
Interesting Posts