python - PyQuery Python 不支持 for 循环

标签 python html python-3.x pyquery

我正在尝试编写一个程序,从 .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 循环?当它做一些更简单的事情时,例如连接文件的各个行,它显然可以工作。

最佳答案

问题是您从文件 (links.txt) 中读取的每一行中都有额外的换行符。尝试在 links.txt 中打开另一行,您会发现即使是最后一个条目也不会被处理。

我建议您在 for 之后的行变量上进行右侧删除,如下所示:

for line in links:
    line = line.rstrip()
    r = requests.get(line)
    ...

应该可以。

我还认为您不需要请求来获取 html。尝试 results = PyQuery(line) 看看它是否有效。

关于python - PyQuery Python 不支持 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26670972/

相关文章:

javascript - 如果用户在输入框中键入内容,如何触发单击按钮

python - Xlsxwriter Python3 错误

python - 根据 pandas dataframe 的连接数自动向 networkx 中的边添加权重

python - 将 Counter 编码为 Json 对象

python - 生成随机 float

使用 innerHTML 时 JavaScript 不工作

python - Orca 的替代方案,用于创建包含图像和图形的 PDF 文件

jquery - 多步进度条更改输入字段中回车键的状态

python - 在 Python 中将 1 加到 16 字节的数字

Python 在相互依赖的类实例中使用 setter