0

所以我试图在互联网上阅读一个网页,它可以工作,但它给了我整个页面,我想从中复制一个特定的单词,而不是更多。基本上是这样的 API URL,http://api.formice.com/tribe/stats.json?n=Safwanrockz 如果我只想复制“rank”值怎么办?这是我的代码:

import shutil
import os
import time
import datetime
import math
import urllib
from array import array

filehandle = urllib.urlopen('http://api.formice.com/tribe/stats.json?n=Safwanrockz')

for lines in filehandle.readlines():
print lines

filehandle.close()
4

3 回答 3

0

You have 2 main alternatives:

  1. Decoding the JSON object using the standard json module (or similar).
  2. Using a regular expression.

I'd recommend the first alternative because it's more structured and stable, and would work if your requirements get more complex.

于 2013-08-28T22:15:15.830 回答
0

通过将其加载json.loads()到 python中dict

import json
import urllib2

response = urllib2.urlopen('http://api.formice.com/mouse/stats.json?n=Safwanrockz')
data = json.loads(response.read())

print type(data)  # prints <type 'dict'>

print data['tribe']  # prints "Three Feathers"
于 2013-08-28T22:23:14.767 回答
0
import urllib
import json

data = urllib.urlopen('http://api.formice.com/tribe/stats.json?n=Safwanrockz').read()
json_data = json.loads(data)
print data
print json_data['error']

data是来自文档的原始数据,json_data是 JSON 解析的文档(解析为字典)。第一条print语句打印原始数据。第二个打印 JSON 元素的值error

于 2013-08-28T22:29:31.280 回答