Jsoup:如何获取图像的绝对URL?

时间:2011-02-02 13:35:02

标签: jsoup

jsoup中有没有办法提取图像绝对网址,就像人们可以获得链接的绝对网址一样?

考虑http://www.example.com/

中的以下图像元素
<img src="images/chicken.jpg" width="60px" height="80px">

我想获得http://www.example.com/images/chicken.jpg。我该怎么办?

4 个答案:

答案 0 :(得分:66)

获得图像元素后,例如:

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

可替换地:

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

Jsoup在所有节点上都有一个内置absUrl()方法,使用节点的基本URL(可能与检索文档的URL不同)将属性解析为绝对URL。

另请参阅Working with URLs jsoup文档。

答案 1 :(得分:8)

Document doc = Jsoup.connect("www.abc.com").get();
Elements img = doc.getElementsByTag("img");
for (Element el : img) {
String src = el.absUrl("src");
System.out.println("Image Found!");
System.out.println("src attribute is : "+src);
getImages(src);
}

答案 2 :(得分:2)

我们假设您要解析http://www.example.com/index.html

使用jsoup提取img src,它为您提供:images/chicken.jpg

然后,您可以使用URI类将其解析为绝对路径:

URL url  = new URL("http://www.example.com/index.html");
URI uri = url.toURI();
System.out.println(uri.resolve("images/chicken.jpg").toString());

打印

http://www.example.com/images/chicken.jpg

答案 3 :(得分:0)

它可能在div类中,所以代码就像这样(仅作为示例)

session.dataTask(with: request, completionHandler:{( data , response , error) -> Void in
    if let data = data {
            if let jsonObj = try? JSONSerialization.jsonObject(with: data , options: .allowFragments) as! Any {
        print(jsonObj)
                if  let postdata = (jsonObj as AnyObject).value(forKey: "postdata") {
                    print(postdata)
                    //if let something = postdata["best_before"] as? NSDictionary{
                       // print(something)
相关问题