我有这个:
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/