【问题标题】:extract data from a dictionary returned by pycurl从 pycurl 返回的字典中提取数据
【发布时间】:2013-03-05 10:03:29
【问题描述】:

我有这个:

import pycurl
import pprint
import json

c = pycurl.Curl()
c.setopt(c.URL, 'https://mydomainname.com')

c.perform()

上面的代码返回一个像这样的字典:

{"name":"steve", "lastvisit":"10-02-2012", "age":12}

我想遍历那个字典并得到年龄:

age : 12

我试过了:

diction = {}
diction = c.perform()
pprint.pprint(diction["age"])

没有数据返回,我收到了这个错误:

TypeError: 'NoneType' object is unsubscriptable

【问题讨论】:

  • 谢谢你!知道如何计算年龄吗?
  • 我假设您使用的是 Python 3(根据例外情况判断,python 3.1 或 3.2)。

标签: python dictionary pycurl


【解决方案1】:

c.perform() 不返回任何内容,您需要配置一个类似文件的对象来捕获该值。 BytesIO object 可以,然后您可以在调用完成后调用.getvalue()

import pycurl
import pprint
import json
from io import BytesIO

c = pycurl.Curl()
data = BytesIO()

c.setopt(c.URL, 'https://mydomainname.com')
c.setopt(c.WRITEFUNCTION, data.write)
c.perform()

dictionary = json.loads(data.getvalue())
pprint.pprint(dictionary["age"])

如果您未与pycurl 结婚,您可能会发现requests 要容易得多:

import pprint
import requests

dictionary = requests.get('https://mydomainname.com').json()
pprint.pprint(dictionary["age"])

即使是标准库urllib.request module 也会比使用pycurl 更容易:

from urllib.request import urlopen
import pprint
import json

response = urlopen('https://mydomainname.com')
dictionary = json.load(response)
pprint.pprint(dictionary["age"])

【讨论】:

  • 非常感谢 Metijn,我尝试了代码,我得到了这个错误:AttributeError: getvalue
  • @mongotop:抱歉,我没有详细阅读documentation。你为什么使用pycurl?为什么不使用更方便的库?
  • 老实说,这是我所知道的,请您推荐另一个库。
  • 你的代码就像一个魅力!!!!我现在正在阅读有关请求的内容。非常感谢你教育我!!!!非常感谢!!!
  • @MartijnPieters 是否可以使用requests 来模仿curl 'some_url' -d 'some_json'?我找不到这样做的方法。
猜你喜欢
  • 2016-03-25
  • 2021-10-14
  • 1970-01-01
  • 1970-01-01
  • 2016-04-28
  • 2021-11-25
  • 2019-08-12
  • 2020-11-23
  • 2016-11-19
相关资源
最近更新 更多