从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
1 个回答
18
c.perform()
这个方法不会返回任何东西,你需要设置一个像文件一样的对象来捕获这个值。可以使用一个 BytesIO
对象,在调用完成后,你可以在这个对象上调用 .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
模块 使用起来也比 pycurl
更简单:
from urllib.request import urlopen
import pprint
import json
response = urlopen('https://mydomainname.com')
dictionary = json.load(response)
pprint.pprint(dictionary["age"])