需要帮助将数据导出到JSON文件

时间:2014-11-24 10:26:20

标签: python json mongodb beautifulsoup web-crawler

我只是进入编码并在Python中编码。目前我正在使用webcrawler。 我需要将我的数据保存到JSON文件,以便将其导出到MongoDB中。

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.

2 个答案:

答案 0 :(得分:2)

one 列表中创建字典,然后将该列表保存到JSON文件中,以便一个有效的JSON对象:

soupamd = BeautifulSoup(amd.content) 
products = []

for item in soupamd.select("div.listRow"):
    prodname = item.find("span", class_="name")
    adinfo = item.find("span", class_="additional")
    formfactor, grafisch, socket = item.find_all("span", class_="info")[:3]
    prijs = item.find("span", class_="price")
    products.append({
        'prodname': prodname.text.strip(),
        'adinfo': adinfo.text.strip(),
        'formfactor': formfactor.text.strip(),
        'grafisch': grafisch.text.strip(),
        'socket': socket.text.strip(),
        'prijs': prijs.text.strip(),
    })

with open("mobos.json", "w") as outfile:
    json.dump(products, outfile)

如果你真的想要生成单独的JSON对象,每行一个,在两者之间写下换行符,这样你至少可以再次找到这些对象(否则解析将是一个野兽):

with open("mobos.json", "w") as outfile:
    for product in products:
        json.dump(products, outfile)
        outfile.write('\n')

因为我们现在有一个对象列表,所以使用for循环遍历该列表会更简单。

与您的代码存在其他一些差异:

  • 使用list.append()而不是list.insert();当有任务的标准方法时,不需要这种冗长的代码。
  • 如果您只想查找一个匹配项,请使用element.find()而不是element.find_all()
  • 你真的想避免使用blanket exception handling;你掩饰的远远超过你想要的。仅捕获特定的例外。
  • 我使用str.strip()删除通常在HTML文档中添加的额外空格;您还可以添加额外的' '.join(textvalue.split())来删除内部换行符并折叠空格,但此特定网页似乎不需要该措施。

答案 1 :(得分:0)

由于OP希望使用带有类似字典的对象的JSON,并且没有指定它们应位于JSON的列表中,因此此代码可能会更好地工作:

outFile = open("mobos.json", mode='wt')
for item in soupamd.select("div.listRow"):
    prodname = item.find("span", class_="name")
    adinfo = item.find("span", class_="additional")
    formfactor, grafisch, socket = item.find_all("span", class_="info")[:3]
    prijs = item.find("span", class_="price")
    tempDict = {
        'prodname': prodname.text.strip(),
        'adinfo': adinfo.text.strip(),
        'formfactor': formfactor.text.strip(),
        'grafisch': grafisch.text.strip(),
        'socket': socket.text.strip(),
        'prijs': prijs.text.strip(),
    }
    json.dump(tempDict, outFile)
outFile.close()

由于json.dump会自动处理新行,因此无需写新行。