如何从Jsoup中的“ a”标签获取属性“ href”?

时间:2018-07-06 17:41:21

标签: java android web-scraping jsoup

我正在做一个网络抓取项目,基本上是从Google图片中获取图片。为了获得图像src,我使用

Element.attr("href")

但是,它返回

#

我的代码

Document shivWall = Jsoup.connect(searchURL).get();
Elements smallImgElements = shivWall.getElementsByClass("rg_bx rg_di rg_el ivg-i");
smallImgElements.get(0).select("a.rg_l").get(0).attr("href");

我尝试了很多方法,但是没有一个起作用。我什至通过将attr参数更改为某个随机值来再次检查,它按预期返回null。但是,对于“ href”,它仅返回“#”。请帮忙。

2 个答案:

答案 0 :(得分:0)

要从网站上获取标签的 src属性,您可以尝试使用以下代码段

public class DownloadImages {

    //The url of the website. This is just an example
    private static final String webSiteURL = "http://www.supercars.net/gallery/119513/2841/5.html";

   //The path of the folder that you want to save the images to
   private static final String folderPath = "<FOLDER PATH>";

   public static void main(String[] args) {

   try {
     //Connect to the website and get the html32
     Document doc = Jsoup.connect(webSiteURL).get();

     //Get all elements with img tag ,
     Elements img = doc.getElementsByTag("img");

     for (Element el : img) {
         //for each element get the srs url
         String src = el.absUrl("src");

         System.out.println("Image Found!");

         System.out.println("src attribute is : "+src);

         getImages(src);

   }


} catch (IOException ex) {
   System.err.println("There was an error");
   Logger.getLogger(DownloadImages.class.getName()).log(Level.SEVERE, null, ex);

     }

}

private static void getImages(String src) throws IOException {
     String folder = null;

     //Exctract the name of the image from the src attribute
     int indexname = src.lastIndexOf("/");

     if (indexname == src.length()) {
         src = src.substring(1, indexname);

        }

        indexname = src.lastIndexOf("/");

        String name = src.substring(indexname, src.length());

        System.out.println(name);

        //Open a URL Stream

        URL url = new URL(src);

        InputStream in = url.openStream();

        OutputStream out = new BufferedOutputStream(new FileOutputStream( folderPath+ name));

        for (int b; (b = in.read()) != -1;) {

            out.write(b);

        }

        out.close();

        in.close();

    }

}

这是使用Jsoup从网站下载图像的方法。

希望这会有所帮助。

答案 1 :(得分:0)

如果您检查通过Document shivWall = Jsoup.connect(searchURL).get();获得的html结构,您会发现#href参数的初始值。加载页面后,将使用javascript动态添加网址。 Jsoup无法处理此问题。

要获取网址,您可以使用以下代码:

for(Element e : shivWall.select(".rg_meta.notranslate")) {
    Gson gson = new Gson();
    Map imageData = gson.fromJson(e.text(), Map.class);
    System.out.println(imageData.get("ou"));
}