抓取站点



我正在尝试编写一个警报系统,定期刮掉投诉板网站,以查找有关我的产品的任何投诉。我用Jsoup做同样的事情。下面是给我错误的代码片段。

doc = Jsoup.connect(finalUrl).timeout(10 * 1000).get();

显示错误

java.net.SocketException: Unexpected end of file from server

当我在浏览器中复制粘贴相同的finalUrl字符串时,它可以工作。然后我尝试了简单的URL连接

            BufferedReader br = null;
            try {
                URL a = new URL(finalUrl);
                URLConnection conn = a.openConnection();
                // open the stream and put it into BufferedReader
                br = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                doc = Jsoup.parse(br.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }

但事实证明,连接本身返回null (br为null)。现在的问题是,为什么相同的字符串当复制粘贴在浏览器打开网站没有任何错误?

完整的堆栈跟踪如下:

java.net.SocketException: Unexpected end of file from server
    at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:774)
    at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:633)
    at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:771)
    at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:633)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1195)
    at ComplaintsBoardScraper.main(ComplaintsBoardScraper.java:46)

这个很棘手!: -)

服务器阻止所有没有正确的用户代理的请求。这就是为什么你的浏览器成功了,而Java却失败了。

幸运的是,在jsoup中更改用户代理不是什么大事:

final String url = "http://www.complaintsboard.com/?search=justanswer.com&complaints=Complaints";
final String userAgent = "Mozilla/5.0 (X11; U; Linux i586; en-US; rv:1.7.3) Gecko/20040924 Epiphany/1.4.4 (Ubuntu)";
Document doc = Jsoup.connect(url) // you get a 'Connection' object here
                        .userAgent(userAgent) // ! set the user agent
                        .timeout(10 * 1000) // set timeout
                        .get(); // execute GET request

我已经采取了第一个用户代理,我发现…我猜你可以使用任何有效的,而不是太。

最新更新