mon*_*top 5 python dictionary pycurl
我有这个:
import pycurl
import pprint
import json
c = pycurl.Curl()
c.setopt(c.URL, 'https://mydomainname.com')
c.perform()
Run Code Online (Sandbox Code Playgroud)
上面的代码返回一个这样的字典:
{"name":"steve", "lastvisit":"10-02-2012", "age":12}
Run Code Online (Sandbox Code Playgroud)
我想循环通过该字典并获得年龄:
age : 12
Run Code Online (Sandbox Code Playgroud)
我试过了:
diction = {}
diction = c.perform()
pprint.pprint(diction["age"])
Run Code Online (Sandbox Code Playgroud)
没有数据返回,我收到此错误:
TypeError: 'NoneType' object is unsubscriptable
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 15
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"])
Run Code Online (Sandbox Code Playgroud)
如果你没有结婚pycurl,你可能会发现requests更容易:
import pprint
import requests
dictionary = requests.get('https://mydomainname.com').json()
pprint.pprint(dictionary["age"])
Run Code Online (Sandbox Code Playgroud)
甚至标准库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"])
Run Code Online (Sandbox Code Playgroud)