如果您尝试转到不存在的 tumblr 页面,我想抓取重定向的 tumblr 站点。如果我将 URL 放入浏览器,我就会到达重定向的站点。然而,Jsoup 只是返回一个“HTTP error fetching URL.Status=404”错误。有什么建议吗?
String userAgent = "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6";
Document doc = Jsoup.connect("http://www.faszokvagyunk.tumblr.com").userAgent(userAgent).followRedirects(true).get();
谢谢。
最佳答案
您的代码似乎可以很好地处理其他类型的重定向,但是,对于 tumblr,您会得到一个导致 404 状态的 404 页面,因此出现异常,并且可能有很多原因:
- 重定向可能根本不会发生
- Tumblr 确实以一种奇怪的方式重定向
- Tumblr 不必要的返回 404 导致异常
- 其他可能性
我不知道这个解决方案是否可以帮助您,但是,您实际上可以通过如下链接方法来指示您的 JSOUP 连接忽略 HttpErrors(这至少允许您验证 http 错误):
Document doc = Jsoup.connect("http://oddhouredproductivity.tumblr.com/tagged/tips").userAgent(userAgent).followRedirects(true).ignoreHttpErrors(true).get();
ignoreHttpErrors 指示连接在遇到 404、500 等错误状态代码时不要抛出 Http 错误。
Connection ignoreHttpErrors(boolean ignoreHttpErrors)
Configures the connection to not throw exceptions when a HTTP error occurs. (4xx - 5xx, e.g. 404 or 500). By default this is false; an IOException is thrown if an error is encountered. If set to true, the response is populated with the error body, and the status message will reflect the error.
Parameters: ignoreHttpErrors - - false (default) if HTTP errors should be ignored.
Returns: this Connection, for chaining
如果您将 ignoreHttpErrors 设置为 true,那么您将获得文档。如果不是,则 Document 将为空。
我也遇到了这个 site这可能实际上展示了实际的 tumblr 重定向。您可能希望使用该页面中的 URL 进行测试,因为它们是正确的 tumblr 重定向。如果您查看此页面的检索文档,您会看到 3 秒后触发的 JavaScript 直接函数,如下所示:
//redirect to new blog
setTimeout( redirectTumblr, 3000 );
function redirectTumblr() {
location.replace('http://oddhour.tumblr.com' + location.pathname);
}
当我连接到您在问题中提供的 URL 时。我看到 404 页面并且通过连接在文档中返回的 404 页面的内容不包含重定向的迹象(就像其他页面一样)。
关于java - 如何使用 Jsoup 跟踪来自 404 的重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33769950/