使用python从网页获取数据并将其下载输出到文件

时间:2014-01-19 20:25:02

标签: python json scripting

我正在尝试使用python和JSON从网页(http://www.usgs.gov/)中获取一些数据。当我执行这个脚本时(我在一个教程中找到了这个脚本)它工作正常,但是当我试图将此输出输入到本地文件时,我在最后两行中遇到一些错误,说的语法无效( “:”)并且当我插入f.close()时也出现错误我用Google搜索并更改了一些脚本但它不起作用。需要帮助来解决这个问题。我使用的是Python IDLE 2.7.5版。

    import urllib2
    import json

    #Example file to parse and process JSON
    f = open("output.txt")

    #use the JSON module to load the string into a dictionary
    def printResults(data):
        theJSON = json.loads(data)

    #access the contents of JSON like any othe object
        if "title" in theJSON["metadata"]:
            f.write( theJSON["metadata"]["title"])

    #output the no of events + magnitude and each event name
        count = theJSON["metadata"]["count"];
        f.write( str(count) + " events recorded")

    def main():
        urlData = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_hour.geojson"

    #open the url and read the data
       webUrl = urllib2.urlopen(urlData)
       print webUrl.getcode()
       if (webUrl.getcode() == 200):
          data = webUrl.read()
          printResults(data)
       else:
          f.write( "Received an error from server,can't retrieve results" + str(webUrl.getcode())

    if __name__=="__main__":
       main()

2 个答案:

答案 0 :(得分:1)

你错过了这一行的结束括号:

 f.write( "Received an error from server,can't retrieve results" + str(webUrl.getcode())

另外,你的缩进不一致。您需要确保缩进始终是四个空格。最好使用自动为您执行此操作的编辑器。

got errors as well when i insert f.close()

虽然这总是一个好习惯,但您不需要在python中显式关闭文件。它们在被垃圾收集时将被关闭(通常,在没有对象的引用之后,例如在程序终止时,在这种情况下)

答案 1 :(得分:0)

我在这个脚本中进行了2次更改,我认为脚本工作正常。 第一个,我将第二个参数添加到open函数中,写入为'w',

**f = open("output.txt",'w')**

,第二行是文件的最新行,如下所示:

if (webUrl.getcode() == 200):
    data = webUrl.read()
    printResults(data)
else:
    f.write( "Received an error from server,can't retrieve results" + str(webUrl.getcode()))

小心缩进,不要忘记括号!