获取KeyError:在我的Python脚本中

时间:2016-03-06 11:38:11

标签: json python-2.7

我正在尝试构建将使用Python下载图像的脚本。我在代码中遇到问题,因为Python v 2.7.11中的keyerror正在发生。我的代码是

import urllib, urllib2, demjson, os
json = demjson.JSON()
def read_newbooks_file(path):

data = open(path)
isbnlist = []
for isbn in data.readlines():
    isbnlist.append(isbn.replace("\n",""))
return isbnlist

isbns = read_newbooks_file("C:\\newbooks.txt")
print isbns
for isbn in isbns:
    url="http://openlibrary.org/api/search?q={%22query%22:%22(isbn_10:(" + isbn + ")%20OR%20%20isbn_13:(" + isbn + "))%22}"
    response=urllib.urlopen(url)
    book=json.decode(response.read())
    if book["result"]!=[]:
        results = book["result"]
        print results
        url = "http://openlibrary.org/api/get?key=" + results[0]
        OLResult=urllib.urlopen(url)
        data=demjson.decode(OLResult.read())
        print data
        imgurl = 'http://covers.openlibrary.org/b/olid/' + results[0][3:] + '-M.jpg'
        imgfile = urllib.urlretrieve(imgurl, "C:\\" + isbn + ".jpg")
        fsize = os.path.getsize(imgfile[0])
        if fsize < long(1000):
            os.remove("C:\\" + isbn + ".jpg")
        gparams = urllib.urlencode({'bibkeys': isbn, 'jscmd':'viewapi','callback':'gcallback'})
        opener = urllib2.build_opener(urllib2.HTTPHandler())
        request = urllib2.Request('http://books.google.com/books?%s' % gparams)
        opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')]
        g = opener.open(request).read()
        print g
        if g != "gcallback({});":
            g = g[10:-2]
            gbookinfo=demjson.decode(g)
        if gbookinfo[isbn].has_key("info_url"):
            print "GB info url: " + gbookinfo[isbn]["info_url"]
        if gbookinfo[isbn].has_key("thumbnail_url"):
            print "GB thumbnail url: " + gbookinfo[isbn]["thumbnail_url"]
            opener = urllib2.build_opener(urllib2.HTTPHandler())
            request = urllib2.Request(gbookinfo[isbn]["thumbnail_url"])
            opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')]
            picfile = open("C:\\" + isbn + "-g.jpg", "w+b")
            picfile.write(opener.open(request).read())

我得到的错误是

Traceback (most recent call last):
  File "C:/Python25/first.py", line 16, in <module>
    if book["result"]!=[]:
KeyError: 'result'

1 个答案:

答案 0 :(得分:0)

variable RT : std_logic_vector(127 downto 0) := ( 0 => '1', 1 => '1', 2 => '1', 3 => '1', others => '0' ); 为空时,或者您尝试检查某个值的密钥是否存在时,您将收到密钥错误。  您可以使用book检查in中是否存在密钥 例如,如果dict为空或缺少您的密钥,则可以使用以下内容:

book

这样,您就知道密钥存在,并且您的if 'result' in book: book['result'] = ..... # Do something 是一个无法引发密钥错误的有效语句。此外,它还可以帮助您调试,例如您的book['result ']词典是空的还是没有您想要的密钥。

希望有所帮助