2012-11-27 104 views
2

我需要创建cronjob来测试网站是否每隔一小时检索一次数据。如何使用Python从网站获取和验证JSON数据?

最初尝试将json数据粘贴到文本文件中,并通过编码和解码来验证数据。现在我需要每次运行cron作业时都要加载实时数据(json数据)。使用urllib2,但它没有从url获取请求响应。

Url - > on loading - >通过firebug给url执行并从那里json数据。我如何可以导入或解析这种URL到Python。请给我一个例子。

我的步骤: 创建shedule

 1.45 08 * * 1-5 /home/user/myfile/daily_verifydata.sh >> /home/user/cronlog.log 

daily_verifydata.sh

#!/bin/sh 
    python /home/user/path/Dashboard_test.py 

Dashboard_test.py

import json 
    import urllib2 

    f = open('test.txt','r') # open in read mode 
    data = f.read() 
    print data 

    # How to Parse the json from the URL to python 

    data_string = json.dumps(data) 
    print '\n''ENCODED:', data_string 

    decoded = json.loads(data_string) 
    print '\n''DECODED:', decoded 

    # Validating data through decoded output. 

如果有可能通过卷曲解析,需要知道的语法

谢谢,维杰

+1

我没有看到'cron'在那里有多相关。请尽量在将来只将相关信息放入您的问题中。 –

+0

你想要提交什么网址?请张贴您的urllib2尝试 – dm03514

回答

1

我建议使用请求

import requests 
import simplejson 

session = requests.session() 
# I presume your site has authentication 
response = session.post(URL_TO_LOGIN, { 
      'username': username, 
      'password': password 
     }) 
response = session.get(URL_TO_JSON) 
if response.ok: 
    simplejson.loads(response.text) 
1

对于bash脚本retrieveing您的JSON - 您可以使用好的工具httpie

如果你想从python脚本拉JSON - 最好的选择是requests lib

而且为了验证,它很复杂 - JSONSchema