与urllib的cookie [英] Cookies with urllib

查看:266
本文介绍了与urllib的cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能看起来像一个非常简单的问题,我很困惑为什么这对我很难。

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

我想写一个函数它需要三个输入:[url,data,cookies],它将使用urllib(而不是urllib2)来获取请求的URL的内容。
我想这很简单,所以我写了以下:

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

这不起作用,据我所知

推荐答案

你没有说出你试过的时候出了什么问题,重新测试。请求是否完成?服务器无法识别您的Cookie?跳出我的一个事情是,你可能加入多个cookie到一个单一的头字段。如果您使用单独的 Cookie:头字段,它是否有效?

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?

这篇关于与urllib的cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆