Bruno Caetano Bruno Caetano - 3 months ago 9
Python Question

Retrieve image from method called by URL in python

I'm trying to retrieve an image that is returned through a given URL using python, for example this one:

http://fundamentus.com.br/graficos3.php?codcvm=2453&tipo=108

I am trying to do this by using urllib retrieve method:

import urllib

urlStr = "http://fundamentus.com.br/graficos3.php?codcvm=2453&tipo=108"
filename = "image.png"
urllib.urlretrieve(urlStr,filename)


I already used this for other URLs, (such as http://chart.finance.yahoo.com/z?s=CMIG4.SA&t=9m), but for the first one it's not working.

Does anyone have an idea about how to make this for the given URL?
Note: I'm using Python 2.7

Answer

You need to use a session which you can do with requests:

import requests

with requests.Session() as s:
    s.get("http://fundamentus.com.br/graficos.php?papel=CMIG4&tipo=2")
    with open("out.png", "wb") as f:
       f.write(s.get("http://fundamentus.com.br/graficos3.php?codcvm=2453&tipo=108").content)

It works in your browser as you had visited the initial page where the image was so any necessary cookies were set.

Comments