我使用python 2.7.2的代码有什么问题 我正在尝试创建一个python脚本,可以自动查找歌曲的歌词,这是我一直在做的项目
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
请帮帮我
答案 0 :(得分:1)
你应该看看实际的反应是什么。当我尝试使用这些参数的URL时,我会得到一个mediawiki帮助页面;通过阅读,您似乎需要提供action
参数,其值为lyrics
。
query = urllib.urlencode(dict(action='lyrics', artist=artist, song=song, fmt="realjson"))