EHarpham
EHarpham

Reputation: 622

Grabbing a selected number of images from a site with Jsoup

I require the first 5 images of type jpg from 3 different sites. Currently i am using:

Document doc = Jsoup.connect(URL).timeout(10*1000).get();
Elements jpgs = doc.select("img[src$=.jpg]");

To grab the jpgs from a single site and save them into an ArrayList and then add them to a JPanel. This means i can only use one site however i would like to have mixed results of the images from 3 (or more) sites.

Using .first and then writing code to ignore the previously grabbed elements would be one option but is not very clean.

Any suggestions would be greatly appreciated.

Thanks

Upvotes: 0

Views: 410

Answers (1)

pbojinov
pbojinov

Reputation: 927

Here's a possible solution, it would just entail adding the sites you want to get content from to an ArrayList.

Connect to a site, append the number of images you want to ArrayList images, then repeat this process for each site you want to get content from.

ArrayList<String> sites = new ArrayList<String>();
ArrayList<String> images = new ArrayList<String>();  
sites.add("http://google.com);
sites.add("http://facebook.com");
sites.add("http://stackoverflow.com");
int numSites = sites.size();

//number of images you want from each site
int maxNum = 5; 

for (int i = 0; i < numSites; i++) {
      //iterate through images and save first 5 or however many you choose
      for (Elements jpg : jpgs) {
      while (maxNum > 0) {
         images.add(jpg.attr("abs:src"));
         maxNum--;
      }
}

Then connect to the next site and repeat this process for how ever many sites you want to get content from.

Hope this helps.

Upvotes: 1

Related Questions