我尝试从api中提取歌词,并将响应直接打印到csv
文件,如下所示:
def scrape_genius_lyrics(urls):
all_lyrics=[]
headers = {'Authorization': 'mytoken'}
base_url = 'https://genius.com/'
with codecs.open('genius.csv', 'ab', encoding='utf8') as outputfile:
outwriter = csv.writer(outputfile)
for url in urls:
page_url = base_url + url
try:
page = requests.get(page_url, headers=headers)
html = BeautifulSoup(page.text, "html.parser")
[h.extract() for h in html('script')]
lyrics = html.find('div', class_='lyrics').get_text()
# outwriter.writerow(lyrics)
all_lyrics.append(lyrics)
print lyrics
except:
'could not find page for {}'.format(url)
但是,我只在注释#outwriter.writerow(lyrics)
时才看到响应,否则程序将停止并且不打印歌词。你知道吗
如何在每次迭代中将每个歌词保存到它自己的行csv
文件中?你知道吗
您可能应该缩进for循环以保持writer打开。你知道吗
当您将相同的信息写入文件时,您还应该决定是否真的需要将
all_lyrics
存储在内存中。你知道吗您可以随时重新打开该文件并在稍后获取
all_lyrics
。你知道吗相关问题 更多 >
编程相关推荐