【问题标题】:Equivalent implementation of curl request using urllib2使用 urllib2 等效实现 curl 请求
【发布时间】:2015-06-22 16:54:39
【问题描述】:

我有一个curl 命令:

curl -H 'XXX:1' -b headerinfo https:.....com/getinfo

但是,我想用 Python 做同样的事情。 我尝试了以下方法:

with open('headerinfo', 'r') as headerfile:
    newData = headerfile.read()

req = urllib2.Request("https:....com/getinfo ", newData)
req.add_header('XXX', '1')
res2 = urllib2.urlopen(req)

但是,上面的代码不起作用。有什么我遗漏的东西阻止了我的代码工作吗?

【问题讨论】:

  • 您从 python 代码中看到了什么错误?
  • 我不认为这是 python 错误.. 我得到“urllib2.HTTPError: HTTP Error 401: Unauthorized”.. 可能是因为 headerinfo 没有正确发送.. 不确定
  • “它不起作用”非常模糊。如果您确切地指定它是如何不工作的可能会很好 - 错误消息、日志文件、异常等......

标签: python curl urllib2


【解决方案1】:

-b 选项用于将 cookie 发送到 Web 服务器。如果-b 的值为name=value,它将作为cookie 发送,否则该值用作cookie 数据的文件名。

要发送 cookie,您必须创建一个开启程序。

import cookielib, urllib2
cj = cookielib.MozillaCookieJar()
cj.load('headerinfo')
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders.append(('XXX','1'))
response = opener.open("http://example.com/")

【讨论】:

  • 我收到一个错误“cookielib.LoadError: 'headerinfo' 看起来不像 Netscape 格式的 cookies 文件”我该怎么办?
  • 尝试用cookielib.FileCookieJar()替换cookielib.MozillaCookieJar()
  • cookielib.LWPCookieJar() 以与 libwww-perl 库的 Set-Cookie3 文件格式兼容的格式从磁盘加载 cookie 并将其保存到磁盘。使用 linux file 命令检查文件的格式。如果是 sqlite3,则必须将其导出为 Netscape 格式并使用export-cookies
  • with FileCookieJar().. Traceback(最近一次调用最后):文件“curl_json.py”,第 26 行,在 cj.load('headerinfo') 文件“/System/Library /Frameworks/Python.framework/Versions/2.7/lib/python2.7/cookielib.py”,第 1763 行,在加载 self._really_load(f, filename, ignore_discard, ignore_expires) A​​ttributeError: FileCookieJar instance has no attribute '_really_load'
  • 我错了cookielib.FileCookieJar() 是一个不应使用的基类。
猜你喜欢
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-20
  • 2018-12-15
相关资源
最近更新 更多