Search code examples
pythonimagebeautifulsoupscreen-scraping

How to add Text to end of each image name when scraping with Python


I am downloading four images from a website. I want each image to be named the SKU and then (1), (2) etc.

I have managed to write the code to download each file however it is currently overwriting each one as they are all named the same.

What do I need to do in my code to make each one have the number at the end?

for image in images:
    if(image.get('src').startswith('https://imageapi.partsdb.com.au/api/Image')):
        link = (image.get('src'))
        name = soup.find("div",{"class":"head2BR"}).text
        with open(name + '.jpg','wb') as f:
            im = requests.get(link) 
            f.write(im.content)
            print('Writing:', name)

Solution

  • You can use the built-in enumerate() function - which will yield the item along with its index.

    for index, image in enumerate(images, start=1):
        if(image.get('src').startswith('https://imageapi.partsdb.com.au/api/Image')):
            link = (image.get('src'))
            name = f'{soup.find("div", {"class": "head2BR"}).text} ({index})'
    
            with open(name + '.jpg','wb') as f:
                im = requests.get(link) 
                f.write(im.content)
                print('Writing:', name)