我正在尝试从html中提取值,然后将它们转换为json数组,到目前为止,我已经能够获得所需的内容,但只能作为单独的字符串:
我做了两个for循环:
for line in games_html.findAll('div', class_="product_score"):
score= ("{'Score': %s}" % line.getText(strip=True))
print score
for line in games_html.findAll('a'):
title= ("{'Title': '%s'}" % line.getText(strip=True))
print title
产生这两个输出:
{'Title': 'Uncanny Valley'}
{'Title': 'Subject 13'}
{'Title': '2Dark'}
{'Title': 'Lethal VR'}
{'Title': 'Earthlock: Festival of Magic'}
{'Title': 'Knee Deep'}
{'Title': 'VR Ping Pong'}
和
{'Score': 73}
{'Score': 73}
{'Score': 72}
{'Score': 72}
{'Score': 72}
{'Score': 71}
{'Score': 71}
(它们更长,但是您可以通过此获得一个想法...)
如何使用python从其中创建一个json数组,如下所示:
[{'Title': 'Uncanny Valley', 'Score': 73}, {....}]
我之后将使用结果数组做其他事情。...
我是否需要将循环中的项目存储到列表中,然后合并它们?给我一个例子,您能说明一个例子吗?
非常感谢您的帮助,对我来说这是一次非常酷的学习经历,因为到目前为止我只使用过bash。 Python看起来更性感。
您需要维护两个用于乐谱和标题的列表,并将所有数据附加到这些列表中,而不是打印,然后将这些列表与列表推导一起zip
以获得所需的输出为:
import json
scores, titles = [], []
for line in games_html.findAll('div', class_="product_score"):
scores.append(line.getText(strip=True))
for line in games_html.findAll('a'):
titles.append(line.getText(strip=True))
score_titles = [{"Title": t, "Score": s} for t, s in zip(titles, scores)]
print score_titles
# Printing in JSON format
print json.dumps(score_titles)