2017-10-21 49 views
0

我發現這個Python代碼通過自定義搜索查詢刮嘰嘰喳喳:如何使用python刮板將結果保存到csv?

https://github.com/tomkdickinson/Twitter-Search-API-Python/blob/master/TwitterScraper.py

我想從這個代碼的結果存儲到一個CSV文件。

我試圖在內部圍繞線245添加CSV作家循環,打印出的鳴叫按我的搜索查詢,但CSV文件的結果爲空白

def save_tweets(self, tweets): 
    """ 
    Just prints out tweets 
    :return: True always 
    """ 
    for tweet in tweets: 
     # Lets add a counter so we only collect a max number of tweets 
     self.counter += 1 
     if tweet['created_at'] is not None: 
      t = datetime.datetime.fromtimestamp((tweet['created_at']/1000)) 
      fmt = "%Y-%m-%d %H:%M:%S" 
      myCsvRow = log.info("%i [%s] - %s" % (self.counter, t.strftime(fmt), tweet['text'])) 
      fd = open('document.csv','a') 
      fd.write(myCsvRow) 
      fd.close() 

    return True 

另外,有一個在評論代碼在170行左右提到:

@abstractmethod 
def save_tweets(self, tweets): 
    """ 
    An abstract method that's called with a list of tweets. 
    When implementing this class, you can do whatever you want with these tweets. 
    """ 

如何使用此類保存推文?

回答

1

你的問題似乎是行:

myCsvRow = log.info("%i [%s] - %s" % (self.counter, t.strftime(fmt), tweet['text'])) 

看着你使用GitHub的頁面上的代碼,我可以看到log是一個Python記錄器。 log.info的目的是編寫它在某處的字符串(例如:控制檯,文件或這些或其他地方的任何組合)。它不會返回一個值,因此myCsvRow將爲空。

你想要的是更容易:

myCsvRow = "%i [%s] - %s" % (self.counter, t.strftime(fmt), tweet['text']) 

雖然,在一對夫婦的筆記:

(1)你是不是把條目,這是很常見的CSV格式之間的逗號(CSV =逗號分隔值)和

(2)當您的某個字段是可能包含逗號的文本字段時,嘗試寫出csv行實際上是一種風險。如果你天真地只寫出文本,推文中的逗號會導致任何解釋CSV的人認爲該行中有額外的CSV字段。幸運的是python附帶了一個csv庫,它可以幫助你避免這些問題。

+0

感謝您的答案和提示! –