2016-12-16 38 views
0

这个代码有什么问题我正在使用python 2.7.2 我想创建一个python脚本,可以自动查找歌曲的歌词它是一个项目我有一直致力于错误没有JSON对象可以解码

import codecs 
import json 
import sys 
import urllib 
import urllib2 

import bs4 

def extract_lyrics(page): 
    """Extract lyrics text from given lyrics.wikia.com html page.""" 
    soup = bs4.BeautifulSoup(page) 
    result = [] 
    for tag in soup.find('div', 'lyricbox'): 
     if isinstance(tag, bs4.NavigableString): 
      if not isinstance(tag, bs4.element.Comment): 
       result.append(tag) 
     elif tag.name == 'br': 
      result.append('\n') 
    return "".join(result) 

artist = raw_input("Enter artist:") 
song = raw_input("Enter song:") 

query = urllib.urlencode(dict(artist=artist, song=song, fmt="realjson")) 
response = urllib2.urlopen("http://lyrics.wikia.com/api.php?" + query) 
data = json.load(response) 

if data['lyrics'] != 'Not found': 

    print(data['lyrics']) 

    lyrics = extract_lyrics(urllib2.urlopen(data['url'])) 
    filename = "[%s] [%s] lyrics.txt" % (data['artist'], data['song']) 
    with codecs.open(filename, 'w', encoding='utf-8') as output_file: 
     output_file.write(lyrics) 
    print("written '%s'" % filename) 
else: 
    sys.exit('not found') 

它给了我这个错误

Traceback (most recent call last): 
    File "C:\Users\elaya\Desktop\Song.py", line 26, in <module> 
    data = json.load(response) 
    File "C:\Python27\lib\json\__init__.py", line 291, in load 
    **kw) 
    File "C:\Python27\lib\json\__init__.py", line 339, in loads 
    return _default_decoder.decode(s) 
    File "C:\Python27\lib\json\decoder.py", line 364, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode 
    raise ValueError("No JSON object could be decoded") 
ValueError: No JSON object could be decoded 

请帮我

+1

您已检查了'response'变量看它实际上所有 – danidee

回答

1

你应该看看什么反应居然是。当我尝试使用这些参数的URL时,我会得到一个mediawiki帮助页面;通读,似乎你需要提供一个action参数值为lyrics

query = urllib.urlencode(dict(action='lyrics', artist=artist, song=song, fmt="realjson")) 
+0

感谢在返回JSON这么多,你救了我的项目,我真的不知道该怎么感谢你 –