webmagic如何取得跳转后的url
比如说请求http://baike.baidu.com/subview/38681/5279942.htm,然后取得跳转后的http://baike.baidu.com/item/%E9%82%93%E8%B6%85/5681
请问解决了嘛。我也想问这个问题呢。
HttpClient会自动follow 跳转,抓取到的数据会是跳转后的。你只是要获取URL么?
对的,想知道如何拿到跳转后的url地址
有一个方法是直接使用HttpClient val response = httpClient.execute(httpPost, context) val headers = response.getHeaders("Location") println("Redirect Location : " + headers(0).getValue()) 或者 val context = HttpClientContext.adapt(httpContext) val redirectLocations = context.getRedirectLocations() 期待作者给出webmagic上的取得方法
我的解决办法是重写Downloader,在download方法中添加:
// 扩展获取重定向链接
List<URI> uris = requestContext.getHttpClientContext().getRedirectLocations();
if(CollectionUtils.isNotEmpty(uris)) {
request.putExtra("redirectLocation", uris.get(0).toURL().toString());
}
以此来获取重定向链接。
重写downloader,添加 protected String getFinalHTTPLocation(HttpClientRequestContext requestContext) { String last_redirect_url = null; try { HttpHost target = requestContext.getHttpClientContext().getTargetHost(); List<URI> redirectLocations = requestContext.getHttpClientContext().getRedirectLocations(); URI location = URIUtils.resolve(requestContext.getHttpUriRequest().getURI(), target, redirectLocations); logger.debug("Final HTTP location: " + location.toASCIIString()); last_redirect_url = location.toASCIIString(); } catch (URISyntaxException e) { logger.error("getFinalHTTPLocation error",e); } return last_redirect_url; }
楼主可以贴一下完整代码吗 我现在爬取百度搜索页的连接 但是这个链接是一个重定向链接 我想获取重定向后的url 例如https://www.baidu.com/link?url=JSAxMVZ8IeIU6ZynfZbl7PjuzEU4bBQZA0B77NvS4hlfzNBYbLeFZ-J2lH40Q4VBBlPQFvq6nSKjxwvMMI5HK_&wd=&eqid=f27a957b00203fc4000000065d5e80fd
我的解决办法是重写Downloader,在download方法中添加:
// 扩展获取重定向链接 List<URI> uris = requestContext.getHttpClientContext().getRedirectLocations(); if(CollectionUtils.isNotEmpty(uris)) { request.putExtra("redirectLocation", uris.get(0).toURL().toString()); }以此来获取重定向链接。
亲测这个方法可用, 感谢
jsoup有这个 https://my.oschina.net/airship/blog/294553 不知道为什么webmagic的相同方法里返回的不对