Jsoup: how to get an image's absolute url?

r0u1i picture r0u1i · Feb 2, 2011 · Viewed 34.6k times · Source

Is there a way in jsoup to extract an image absolute url, much like one can get a link's absolute url?

Consider the following image element found in http://www.example.com/

<img src="images/chicken.jpg" width="60px" height="80px">

I would like to get http://www.example.com/images/chicken.jpg. What should I do?

Answer

Jonathan Hedley picture Jonathan Hedley · Feb 2, 2011

Once you have the image element, e.g.:

Element image = document.select("img").first();
String url = image.absUrl("src");
// url = http://www.example.com/images/chicken.jpg

Alternatively:

String url = image.attr("abs:src");

Jsoup has a builtin absUrl() method on all nodes to resolve an attribute to an absolute URL, using the base URL of the node (which could be different from the URL the document was retrieved from).

See also the Working with URLs jsoup documentation.