Cookies with urllib

Posted by CMC on Stack Overflow See other posts from Stack Overflow or by CMC
Published on 2010-05-22T01:28:50Z Indexed on 2010/05/22 1:30 UTC
Read the original article Hit count: 407

Filed under:
|
|

This will probably seem like a really simple question, and I am quite confused as to why this is so difficult for me.

I would like to write a function that takes three inputs: [url, data, cookies] that will use urllib (not urllib2) to get the contents of the requested url. I figured it'd be simple, so I wrote the following:

def fetch(url, data = None, cookies = None):
  if isinstance(data, dict): data = urllib.urlencode(data)
  if isinstance(cookies, dict):
    # TODO: find a better way to do this
    cookies = "; ".join([str(key) + "=" + str(cookies[key]) for key in cookies])
  opener = urllib.FancyURLopener()
  opener.addheader("Cookie", cookies)
  obj = opener.open(url, data)
  result = obj.read()
  obj.close()
  return result

This doesn't work, as far as I can tell (can anyone confirm that?) and I'm stumped.

© Stack Overflow or respective owner

Related posts about python

Related posts about urllib