0

I'm trying to build a program in Python that will scrape a website for an image and download it, but the website returns this link:

http://www.tapmusic.net/lastfm/collage.php?user=kogam7&type=7day&size=5x5

Which doesn't have a *.jpg or *.png extension. So when I try to use the following code:

import urllib , urllib2, os , sys , time
img = urllib.urlopen("http://www.tapmusic.net/lastfm/collage.php?user=kogam7&type=7day&size=5x5").read()
hand0 = open("test.jpg" , "w")
hand0.write(img)
hand0.close()

It writes an image that looks like this:

https://i.sstatic.net/yWCBg.jpg

Does anyone know what's going wrong?

2
  • I have just tried the script, it works fine here. (OS X) Commented Feb 28, 2015 at 22:57
  • Using Windows, sorry Commented Feb 28, 2015 at 23:03

2 Answers 2

1
from urllib2 import urlopen

# Use 'wb' over 'w' 
with open('image.jpg', 'wb') as f:
    f.write(urlopen('http://www.tapmusic.net/lastfm/collage.php?user=kogam7&type=7day&size=5x5').read())

Learn more about what 'wb' stands for and why it is required on windows.

What is the 'wb' mean in this code, using Python?

Sign up to request clarification or add additional context in comments.

Comments

0

You must open the output file in binary mode by passing "wb" to open(). This is significant if you are using Windows (which I assume you are because your code should otherwise work), i.e.

import urllib , urllib2, os , sys , time
img = urllib.urlopen("http://www.tapmusic.net/lastfm/collage.php?user=kogam7&type=7day&size=5x5").read()
hand0 = open("test.jpg" , "wb")
hand0.write(img)
hand0.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.