webmagic icon indicating copy to clipboard operation
webmagic copied to clipboard

webmagic如何取得跳转后的url

Open tonglin0325 opened this issue 8 years ago • 9 comments

比如说请求http://baike.baidu.com/subview/38681/5279942.htm,然后取得跳转后的http://baike.baidu.com/item/%E9%82%93%E8%B6%85/5681

tonglin0325 avatar Jul 12 '17 10:07 tonglin0325

请问解决了嘛。我也想问这个问题呢。

yjzfun avatar Jul 15 '17 04:07 yjzfun

HttpClient会自动follow 跳转,抓取到的数据会是跳转后的。你只是要获取URL么?

code4craft avatar Jul 15 '17 08:07 code4craft

对的,想知道如何拿到跳转后的url地址

tonglin0325 avatar Jul 16 '17 12:07 tonglin0325

有一个方法是直接使用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上的取得方法

tonglin0325 avatar Jul 16 '17 15:07 tonglin0325

我的解决办法是重写Downloader,在download方法中添加:

// 扩展获取重定向链接
 List<URI> uris = requestContext.getHttpClientContext().getRedirectLocations();
if(CollectionUtils.isNotEmpty(uris)) {
    request.putExtra("redirectLocation", uris.get(0).toURL().toString());
}

以此来获取重定向链接。

slowrookie avatar Nov 20 '17 02:11 slowrookie

重写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; }

annieaska avatar May 10 '18 02:05 annieaska

楼主可以贴一下完整代码吗 我现在爬取百度搜索页的连接 但是这个链接是一个重定向链接 我想获取重定向后的url 例如https://www.baidu.com/link?url=JSAxMVZ8IeIU6ZynfZbl7PjuzEU4bBQZA0B77NvS4hlfzNBYbLeFZ-J2lH40Q4VBBlPQFvq6nSKjxwvMMI5HK_&wd=&eqid=f27a957b00203fc4000000065d5e80fd

fanshanchao avatar Aug 23 '19 16:08 fanshanchao

我的解决办法是重写Downloader,在download方法中添加:

// 扩展获取重定向链接
 List<URI> uris = requestContext.getHttpClientContext().getRedirectLocations();
if(CollectionUtils.isNotEmpty(uris)) {
    request.putExtra("redirectLocation", uris.get(0).toURL().toString());
}

以此来获取重定向链接。

亲测这个方法可用, 感谢

franck418 avatar Aug 10 '20 07:08 franck418

jsoup有这个 https://my.oschina.net/airship/blog/294553 不知道为什么webmagic的相同方法里返回的不对

Plume3362 avatar Sep 14 '20 08:09 Plume3362