【发布时间】:2014-12-27 13:19:25
【问题描述】:
我正在尝试编写一个程序,该程序从 .txt 文件的每一行中提取 url,并执行 PyQuery 以从 LyricsWiki 中刮取歌词数据,在我真正放入 PyQuery 内容之前,一切似乎都运行良好。对于例如,当我这样做时:
full_lyrics = ""
#open up the input file
links = open('links.txt')
for line in links:
full_lyrics += line
print(full_lyrics)
links.close()
它按预期打印所有内容,一个包含所有数据的大字符串。然而,当我实现实际的 html 解析时,它只从最后一个 url 中提取歌词并跳过所有以前的。
import requests, re, sqlite3
from pyquery import PyQuery
from collections import Counter
full_lyrics = ""
#open up the input file
links = open('links.txt')
output = open('web.txt', 'w')
output.truncate()
for line in links:
r = requests.get(line)
#create the PyQuery object and parse text
results = PyQuery(r.text)
results = results('div.lyricbox').remove('script').text()
full_lyrics += (results + " ")
output.write(full_lyrics)
links.close()
output.close()
我写入 txt 文件以避免 Powershell 出现编码问题。反正我运行程序打开txt文件后,只显示links.txt文件上最后一个链接的歌词。
作为参考,'links.txt' 应该包含几个到歌词维基歌曲页面的链接,如下所示: http://lyrics.wikia.com/Taylor_Swift:Shake_It_Off http://lyrics.wikia.com/Maroon_5:Animals
'web.txt' 应该是一个空白的输出文件。
为什么 pyquery 会破坏 for 循环?当它做一些更简单的事情时,它显然可以工作,比如只是连接文件的各个行。
【问题讨论】:
标签: python html python-3.x pyquery