Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

python - Cookies with urllib

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You didn't say what went wrong when you tried it, or what http server you're testing with. Did the request complete? Did the server fail to recognize your cookies? One thing that jumps out at me is that you're potentially joining multiple cookies into a single header field. Does it work if you use separate Cookie: header fields?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...