2013-03-16 56 views
4

返回我有这样的:提取数据由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 
+0

谢谢Metijn!任何想法如何获得年龄? – mongotop 2013-03-16 19:22:37

+1

我假设你正在使用Python 3(由异常判断,python 3.1或3.2)。 – 2013-03-16 19:35:05

回答

11

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

非常感谢你Metijn,我试了代码,我得到这个错误:'AttributeError:getvalue' – mongotop 2013-03-16 19:26:20

+1

@mongotop:道歉,我没有阅读[文档](http://pycurl.sourceforge.net/doc/ curlobject.html)足够详细。你为什么使用'pycurl'?为什么不使用更方便的库? – 2013-03-16 19:27:54

+0

说实话,那是我知道的那个,你能否建议另外一个图书馆。 – mongotop 2013-03-16 19:29:44