模块urllib.request无法获取数据

时间:2016-07-25 13:29:54

标签: python pycharm urllib2 urllib python-3.5

我正在尝试使用Python 3从lynda测试这个演示程序。我使用Pycharm作为我的IDE。我已经添加并安装了请求包,但是当我运行程序时,它运行干净并显示一条消息“Process finished with exit code 0”,但是没有显示print语句的任何输出。我哪里错了?

import urllib.request # instead of urllib2 like in Python 2.7
import json


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

    # now we can access the contents of the JSON like any other Python object
    if "title" in theJSON["metadata"]:
        print(theJSON["metadata"]["title"])

    # output the number of events, plus the magnitude and each event name
    count = theJSON["metadata"]["count"];
    print(str(count) + " events recorded")

    # for each event, print the place where it occurred
    for i in theJSON["features"]:
        print(i["properties"]["place"])

    # print the events that only have a magnitude greater than 4
    for i in theJSON["features"]:
        if i["properties"]["mag"] >= 4.0:
            print("%2.1f" % i["properties"]["mag"], i["properties"]["place"])

    # print only the events where at least 1 person reported feeling something
    print("Events that were felt:")
    for i in theJSON["features"]:
        feltReports = i["properties"]["felt"]
        if feltReports != None:
            if feltReports > 0:
                print("%2.1f" % i["properties"]["mag"], i["properties"]["place"], " reported " + str(feltReports) + " times")

    # Open the URL and read the data
    urlData = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"
    webUrl = urllib.request.urlopen(urlData)
    print(webUrl.getcode())
    if webUrl.getcode() == 200:
        data = webUrl.read()
        data = data.decode("utf-8") # in Python 3.x we need to explicitly decode the response to a string
    # print out our customized results
        printResults(data)
    else:
        print("Received an error from server, cannot retrieve results " + str(webUrl.getcode()))

3 个答案:

答案 0 :(得分:0)

不确定是否故意将其删除,但此脚本实际上并未执行导入和函数定义之外的任何代码。假设您没有故意将其遗漏,则需要在文件末尾添加以下内容。

if __name__ == '__main__':
    data = "" # your data
    printResults(data)

检查__name__等于"__main__"只是因为您的代码仅在显式运行文件时执行。要在访问文件时始终运行printResults(data)函数(例如,如果将其导入到另一个模块中),您可以在文件底部调用它,如下所示:

data = "" # your data
printResults(data)

答案 1 :(得分:0)

我必须在安装模块后重启IDE。我刚刚意识到并尝试使用“以管理员身份运行”。奇怪的是现在似乎工作。但不确定它是否是一个临时错误,因为即使没有重启,它也能够检测模块及其方法。

答案 2 :(得分:0)

您的评论:重新启动IDE让我觉得pycharm可能无法自动检测新安装的python包。这个答案似乎提供了一个解决方案。

SO answer