1. 程式人生 > >python中向列表中新增字典時,出現前面的覆蓋了後面的

python中向列表中新增字典時,出現前面的覆蓋了後面的

主要問題就是,,字典存入到列表中,其實是將一個引用存入了列表,,如果你每次存入列表中的字典都是在同一個引用下,這時將列表中的字典的引用取出,然後去找對應的值,,,,,如果引用相同,就會出現,遍歷出來的都是最後一條資料的現象, 由於引用指向的地址的內容不斷被覆蓋

下面是我編寫爬蟲程式碼時遇到的問題,在呼叫new_data.getNewBody(new[‘url’])方法返回資料組成的字典時,最後遍歷出現下面圖片中的資料

#得到具體文章的內容類的物件
newsdata = [{},{}]   #這裡只是模擬一個包含字典的列表
new_data = new_Data() #這是一個類
new_detil = []  #這裡儲存所有抓取的資料
for new in newsdata: #通過new_data物件呼叫它裡面的方法,,並且將對應的url傳入 new_body = new_data.getNewBody(new['url']) print(new_body)#列印每條資料 new_detil.append(new_body) print('ok') for aa in new_detil:#遍歷每條資料 print(aa)

這裡我截取了部分資料,,,可以看出上面列印的資料每一條都不一樣,而下面卻都是相同的

這裡寫圖片描述
這裡的資料都是相同的錯誤

這裡附上 ,,new_Data類中的部分程式碼:

#-*- coding:utf-8 -*-
import requests from bs4 import BeautifulSoup from datetime import datetime import pandas import json class new_Data(object): commentUrl = "http://comment5.news.sina.com.cn/page/infoversion=1&format=js& channel=gn&newsid=comos-{}&group=&compress=0&ie=utf-8&oe=utf-8&page=1& page_size=20"
def __init__(self): #具體新聞的資料字典 self.new_body = {} def getNewBody(self,url): ''' 本方法返回具體文章對應的主要內容,返回的是一個數據字典 ''' #new_body = {} res = requests.get(url) res.encoding = 'utf-8' soup = BeautifulSoup(res.text,'html.parser') artibodyTitle = soup.select('#artibodyTitle')[0].text timesouce = soup.select(".time-source")[0].contents[0].strip() dt = datetime.strptime(timesouce,"%Y年%m月%d日%H:%M") #soup.select('.time-source')[0].contents[1].text.strip() media_name = soup.select('.time-source span')[0].text.strip() #print soup.select("#artibody")[0].text article = [] #使用[:-1]是規定迴圈執行到倒數第二個為止,這個目的是不想要最後一條資料 for p in soup.select('#artibody p')[:-1]: article.append(p.text.strip()) #將文章使用換行符連線在一起 art_txt = '\n'.join(article) #print text editor = soup.select('.article-editor')[0].text.lstrip("責任編輯:") #獲得評論數和評論內容 commentCount,comments = self.getCommentsandCounts(url) #評論數 comment = '\n'.join(comments) self.new_body["artibodyTitle"] = artibodyTitle self.new_body["datetime"] = dt self.new_body["media_name"] = media_name self.new_body["article"] = str(art_txt) self.new_body["editor"] = editor self.new_body["commentCount"] = commentCount self.new_body["comments"] = comment return self.new_body

主要問題就出現在下面的程式碼

     def __init__(self):
        #具體新聞的資料字典
        self.new_body = {}
    self.new_body["artibodyTitle"] = artibodyTitle
    self.new_body["datetime"] = dt
    self.new_body["media_name"] = media_name
    self.new_body["article"] = str(art_txt)
    self.new_body["editor"] = editor
    self.new_body["commentCount"] = commentCount
    self.new_body["comments"] = comment
    return self.new_body

這裡是通過初始化方法的方式初始化new_body字典,,,,後面通過self.new_body 的方式新增字典裡的項,,,最後將結果返回給 呼叫它的方法,,,

由於我在呼叫這個方法時,只建立一個類物件,導致後面每次都不在初始化,也就是字典的引用不變, 然後將資料存入後,就會覆蓋原來的,

解決辦法是:
方法一:
不在初始化init()方法中初始化new_body字典,,而是在getNewBody()方法內部建立一個區域性變數,,,,,這樣每次迴圈呼叫這個方法時,都會重建一個new_body = {} 字典…
這裡寫圖片描述

這裡寫圖片描述

方法二:
當然也可不改這些程式碼,,只需每次重新建立一個新的物件也可以解決這個問題,,,但是那樣會消耗很多記憶體,造成記憶體的浪費,,,,所以不推薦這種方式
這裡寫圖片描述