2017-06-14 75 views
0

你能幫我怎麼從字典導入到json文件,我已經從網站獲取所有標籤,但仍然混淆保存所有標籤。這是我的代碼如何添加從美麗的詞典元素到json文件

array= [] 
data = {} 
for divdata in soup.findAll('div', {"class": "ratio9_8 box_img fl mr10"}): 
    for div in divdata.findAll('div', {'class': 'img_con lqd'}): 
     for getatag in div.findAll('a', {'data-category': 'WP Kanal Berita'},href = True): 
      for getimgtag in getatag.findAll('img',title=True,src=True): 
       array.append(getimgtag['title']) 
       array.append(getimgtag['src']) 
       array.append(getatag['href']) 
       data['title'] = array[0] 
       data['image'] = array[1] 
       data['link'] = array[2] 
with open('data.json', 'w') as outfile: 
    json.dump(data, outfile) 
運行程序時

,我只是得到一個字典

{"title": "......", "image": ".....", "link": "...."} 

回答

0

把你的輸出語句在你指定數據的循環。您正在覆蓋每次迭代中的數據。如果你改變你的代碼:

array= [] 
data = {} 
for divdata in soup.findAll('div', {"class": "ratio9_8 box_img fl mr10"}): 
    for div in divdata.findAll('div', {'class': 'img_con lqd'}): 
     for getatag in div.findAll('a', {'data-category': 'WP Kanal Berita'},href = True): 
      for getimgtag in getatag.findAll('img',title=True,src=True): 
       array.append(getimgtag['title']) 
       array.append(getimgtag['src']) 
       array.append(getatag['href']) 
       data['title'] = array[0] 
       data['image'] = array[1] 
       data['link'] = array[2] 
       with open('data.json', 'a') as outfile: 
        json.dump(data, outfile) 

它應該給你你想要的。

或者你可以這樣做:

array= [] 
data = {} 
data_list = [] 
for divdata in soup.findAll('div', {"class": "ratio9_8 box_img fl mr10"}): 
    for div in divdata.findAll('div', {'class': 'img_con lqd'}): 
     for getatag in div.findAll('a', {'data-category': 'WP Kanal Berita'},href = True): 
      for getimgtag in getatag.findAll('img',title=True,src=True): 
       array.append(getimgtag['title']) 
       array.append(getimgtag['src']) 
       array.append(getatag['href']) 
       data['title'] = array[0] 
       data['image'] = array[1] 
       data['link'] = array[2] 
       data_list.append(data) 
data = {'data_list': data_list} 
with open('data.json', 'w') as outfile: 
    json.dump(data, outfile)