我只需进入编码和Python编码。目前我正在研究webcrawler。 我需要将我的数据保存到JSON文件,以便将其导出到MongoDB中。需要帮助将数据导出到JSON文件
import requests
import json
from bs4 import BeautifulSoup
url= ["http://www.alternate.nl/html/product/listing.html?filter_5=&filter_4=&filter_3=&filter_2=&filter_1=&size=500&lk=9435&tk=7&navId=11626#listingResult"]
amd = requests.get(url[0])
soupamd = BeautifulSoup(amd.content)
prodname = []
adinfo = []
formfactor = []
socket = []
grafisch = []
prijs = []
a_data = soupamd.find_all("div", {"class": "listRow"})
for item in a_data:
try:
prodname.insert(len(prodname),item.find_all("span", {"class": "name"})[0].text)
adinfo.insert(len(adinfo), item.find_all("span", {"class": "additional"})[0].text)
formfactor.insert(len(formfactor), item.find_all("span", {"class": "info"})[0].text)
grafisch.insert(len(grafisch), item.find_all("span", {"class": "info"})[1].text)
socket.insert(len(socket), item.find_all("span", {"class": "info"})[2].text)
prijs.insert(len(prijs), item.find_all("span", {"class": "price right right10"})[0].text)
except:
pass
我被困在这部分。我想将我在数组中保存的数据导出为JSON文件。这是我现在有:
file = open("mobos.json", "w")
for i = 0:
try:
output = {"productnaam": [prodname[i]],
"info" : [adinfo[i]],
"formfactor" : [formfactor[i]],
"grafisch" : [grafisch[i]],
"socket" : [socket[i]],
"prijs" : [prijs[i]]}
i + 1
json.dump(output, file)
if i == 500:
break
except:
pass
file.close()
所以我想创建一个字典格式是这样的:
{"productname" : [prodname[0]], "info" : [adinfo[0]], "formfactor" : [formfactor[0]] .......}
{"productname" : [prodname[1]], "info" : [adinfo[1]], "formfactor" : [formfactor[1]] .......}
{"productname" : [prodname[2]], "info" : [adinfo[2]], "formfactor" : [formfactor[2]] .......} etc.
您可能想要阅读关于循环再次和列表的Python教程。不要使用'listobject.insert(len(listobject),...)',例如使用'listobject.append(..)',为什么不把所有的信息添加到**一个**列表中(作为字典,例如),然后只是循环超过一个列表?你可以在'listobject:'中使用'item并且不需要索引。 – 2014-11-24 10:31:55
你真的*不想使用'try ... except'而没有特殊的例外;不要掩盖你的错误。 – 2014-11-24 10:32:51