python - 从 pycurl 返回的字典中提取数据

标签 python dictionary pycurl

我有这个:

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

最佳答案

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"])

关于python - 从 pycurl 返回的字典中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15453608/

相关文章:

python - np.random.permutation, np.random.choice 的时间表现

python - 在打印时如何跳过不在字典中的值

python - 如何使用 pycurl 读取标题

python - 如何捕获作为参数传递给另一个函数的函数的异常

Python - PyQt 信号 - 发出参数并将其发送到不同的类

python - with.ai 中的图像上传功能,无需使用 facebook Messenger

java - 通用工厂和映射值

python - 在字典列表中查找键值,然后替换其他值

python - Django : Fetch XML, 中的 urllib2/pycurl 检查 HTTP 状态,检查 HTTPS 连接

python - 处理 pycurl 在 Twitter streaming api 上挂起