Exceptions while I am extracting data from a Web site

久未见 提交于 2019-12-13 18:37:49

问题


I am using Jsoup to extract data by zip codes from a Web site.The zip codes are read from a text file and the results are written at the console. I have around 1500 zip codes. The program throws two kinds of exceptions:

org.jsoup.HttpStatusException: HTTP error fetching URL. Status=500, URL=http://www.moving.com/real-estate/city-profile/...

java.net.SocketTimeoutException: Read timed out

I thought the solution is to read only few data at the time. So, I used a counter, to count 200 zip codes from the text file and I stop the program for 5 minutes after I have data for 200 zip codes. As I said, I still have the exceptions. So far, when I see the exception, I copy paste the available data, and I continue after that with the following zip codes. But I want to read all data without interruptions. Can be this possible? Any hint will be appreciated. Thank you in advance!

This is my code for reading all data:

    while (br.ready())
        {
            count++;

            String s = br.readLine();
            String str="http://www.moving.com/real-estate/city-profile/results.asp?Zip="+s; 
            Document doc = Jsoup.connect(str).get();

            for (Element table : doc.select("table.DataTbl"))
            {
                for (Element row : table.select("tr")) 
                {
                    Elements tds = row.select("td");
                    if (tds.size() > 1)
                    {
                        if (tds.get(0).text().contains("Per capita income"))
                            System.out.println(s+","+tds.get(2).text());
                    }
                }
            }
            if(count%200==0)
            {
                Thread.sleep(300000);
                System.out.println("Stoped for 5 minutes");
            }
        }

回答1:


Update this line Document doc = Jsoup.connect(str).get(); to set the timeout as:

        Connection conn = Jsoup.connect(str);
        conn.timeout(300000); //5 minutes
        Document doc = conn.get();



回答2:


Connection conn = Jsoup.connect(str); conn.timeout(0); /Infinite Timeout

Set the request timeouts (connect and read). If a timeout occurs, an IOException will be thrown. The default timeout is 3 seconds (3000 millis). A timeout of zero is treated as an infinite timeout.

Parameters:

millis - number of milliseconds before timing out connects or reads.

Returns:

this Connection, for chaining

Source: jsoup API

Set timeout to zero. This way you won'y have to stop for 5 minutes.



来源:https://stackoverflow.com/questions/12984961/exceptions-while-i-am-extracting-data-from-a-web-site

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!