-1

I have a regular expression which scrapes websites for the image names/sources: image is then displayed like this once iv run the code:

[+] 4 images Found:
2018-a-space.JPG
small.jpg
picture.gif
image-certified.jpg

I now want to download these images into a folder within the same working directory. I've had a look at some similar questions on here and most recommend using beautifulsoup which i don't want to use. But dont mind importing other modules if they're appropriate. Thanks in advance.

Bill Bell
  • 21,021
  • 5
  • 43
  • 58
J Doe
  • 113
  • 3
  • 11
  • If the regex part of your code is working as expected please remove it from the question, because it doesn't seem relevant. The question appears to be simply "Given a list of urls, how do I download them?" – Aran-Fey Nov 24 '17 at 15:59
  • Possible duplicate of [Download file from web in Python 3](https://stackoverflow.com/questions/7243750/download-file-from-web-in-python-3) – Spangen Nov 24 '17 at 16:10

1 Answers1

0

No need to read all of that.

Use the requests library — just install it with pip requests install at a command prompt.

You will need the full urls of the images, rather than just the file names, to pass to requests.get, as shown here.

In the open statement you can probably get away with just a file name, as I have, because you want to store the files in the current working directory. Note that the file must be opened 'wb'.

>>> import requests
>>> url = 'https://ichef.bbci.co.uk/news/660/cpsprodpb/AB10/production/_93629734_thinkstockphotos-625798052.jpg'
>>> response = requests.get(url).content
>>> open('squirrel.jpg', 'wb').write(response)
59938

This also assumes that the images are not 'too big'. If they are then you should refer to the documentation for further advice about reading them in smaller pieces.

Bill Bell
  • 21,021
  • 5
  • 43
  • 58