处理json数据时出现问题

时间:2017-11-05 19:05:56

标签: python json python-3.x urllib

目前,当输入是公司(例如LinkedIn)时,代码工作正常并返回正确的消息。电子邮件输入根本不起作用。有什么建议?目前的代码如下:

import urllib
import json

userInput = input('Do you want to find an email (E) or company (C)? ')
userInput = userInput.upper()

def getResponse(url):
    cleanUrl = urllib.parse.quote_plus(url, safe=':/?&=')
    try:
        myRequest = urllib.request.Request(cleanUrl, headers={'User-Agent': 'Chrome'})
        myResponse = urllib.request.urlopen(myRequest).read().decode('utf-8')
        myJSON = json.loads(myResponse)
        return myJSON
    except urllib.error.HTTPError as err:
        print('We failed with error code - ', err.code, '(', err.reason, ')')
        return
    except:
        print("Something else went terribly wrong!")

def takeInput():
    url = 'https://haveibeenpwned.com/api/v2/'
    if userInput == 'E':
        email = input('What email do you want me to search for? ')
        fixedurl = url + 'breachedaccount/' + email
    elif userInput == 'C':
        company = input('What company do you want me to search for? ')
        fixedurl = url + 'breach/' + company 
    else:
        print('Invalid entry. Please type E or C.')

    myJSON = getResponse(fixedurl)
    for data in myJSON:
        name = myJSON.get("Name")
        date = myJSON.get("BreachDate")
        count = myJSON.get("PwnCount")
        itemsLost = myJSON.get("DataClasses")
        print("The", name,"breach occurred on", date,"and", count,"accounts were compromised. Iteams lost include:")
        print(itemsLost)
        break

takeInput()

1 个答案:

答案 0 :(得分:0)

我没有看到休息; 例如:

while True:
     try:
         x = int(input("Please enter a number: "))
         break
     except ValueError:
         print("Oops!  That was no valid number.  Try again...")

如果您想以其他方式执行此操作,您可以查看此文档。取决于你的目标:

http://ozgur.github.io/python-linkedin/