Home / PHP / Web Scraping – fetch all images from a page (Part 2)

Web Scraping – fetch all images from a page (Part 2)

Lets see how to fetch all images from a page by scraping it. If you haven’t read my article on the Introduction of Web Scraping then go through the article and don’t forget to check out the example. Once you have a clear understanding of how Web Scraping works jump to this article to learn more.

I this tutorial I will be showing you how to fetch all images from a flickr page. Let us quickly jumpt to the HTML, javascript (optional) and then PHP.

Markup

The HTML has only three blocks.

  1. Text Field for the URL
  2. Loading Icon
  3. Image Holder

Now send an ajax request to process.php

If the ajax request is successful we iterate through the array and check if the URL is not empty (false). For every valid url we append it to the <img src=”URL”> inside the class imageholder. However this step is optional. You may directly run process.php by hard coding the flickr URL.

PHP

The process.php file uses the same functions mentioned in the preview example (Part 1). Let us see the structure of the page we are going to scrape. We will only be scraping photos from https://www.flickr.com/cameras

Sample link: https://www.flickr.com/cameras/sony/xperia_z3/

You may choose different categories of cameras and models. If you go to the page-source of the target webpage you will find a block which will be like <div id=”thumb-wrapper”>. We will first rip the entire block which contains all the images.

From the HTML code stored in $result we will again rip off <img src=&quot. This will generate a number of code which is equal to the number of images within the ripped block. We need to explode them and put all of them into an array.

Next, iterate through the array and rip only the src attribute of <img> element and push it into an array.

All put together,

That’s it! If you are having hard time trying to understand this code I strongly suggest you to go through Part 1 of Web Scraping. you can find the link at the description of this post or use the search box.

Download Preview

About Ashik

I am a Full Stack Developer and love to work on APIs and Apps. Hardcore lover of Ionic and Laravel <3

Check Also

Weather forecast API using jQuery, Ajax and PHP

Weather forecast API is widely used as widgets in small blogs to huge news website …

Do you wan't to get notified?

I will not spam your inbox. I will only send email whenever I publish a new article or to share information about technology

You have Successfully Subscribed!