1

I want to crawl any website and download only the images. But, with the following code the program is downloading even the gifs that are present in img tag. How can I choose to download only png and jpeg?

def fetch_url():
    url = _url.get()
    config['images'] = []
    _images.set(())
try:
    page = requests.get(url)
except requests.RequestException as rex:
    _sb(str(rex))
else:
    soup = BeautifulSoup(page.content, 'html.parser')
    images = fetch_images(soup, url)
    if images:
        _images.set(tuple(img['name'] for img in images))
        _sb('Images found: {}'.format(len(images)))
    else:
        _sb('No images found!.')
    config['images'] = images


def fetch_images(soup, base_url):
    images = []
    for img in soup.findAll('img'):
        src = img.get('src')
        img_url = ('{base_url}/{src}'.format(base_url=base_url, src=src))
        name = img_url.split('/')[-1]
        images.append(dict(name=name, url=img_url))
    return images
1
  • install wget.. It's a great tool when you want to download images. Nov 16, 2018 at 23:37

3 Answers 3

0

have you tried to append only the formats you want?

def fetch_images(soup, base_url):
    images = []
    for img in soup.findAll('img'):
       src = img.get('src')
       img_url = ('{base_url}/{src}'.format(base_url=base_url, src=src))
       name = img_url.split('/')[-1]
       if name[-3:] == "png" or name[-3:] == "jpg" or name[-4:] == "jpeg": ### <- here
           images.append(dict(name=name, url=img_url))
    return images
0

I would look for the href ending with either .jpeg or .png

soup.select("[href$='.png'], [href$='.jpeg']")
0

Also you can use regex when you are finding tag.

from bs4 import BeautifulSoup
import re
html = """
<html>
  <body>
    <img src="dav.jpg">
    <img src="dav.jpeg">
    <img src="dav.png">
    <img src="dav.pdf"><p>
  </body>
</html>

"""

soup = BeautifulSoup(html,"lxml")
print( soup.find_all("img",src=re.compile(r".*?(?=jpeg|png)")))
# [<img src="dav.jpeg"/>, <img src="dav.png"/>]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.