如何打印sn刮削输出



我正在尝试打印使用snscraper抓取twitter提要的输出。它在命令行上工作,但我不能让它打印到文件。我的代码:

import snscrape.modules.twitter as twitter
maxTweets = 10
keyword='salvation'
for i, tweet in enumerate(twitter.TwitterSearchScraper(keyword + ' since:2021-11-01 until:2023-01-01 lang:"en" ').get_items()):
tweets = {
"tweet.url" : tweet.url
}   
print(tweets)

它打印到命令行,但是当我尝试:

with open('file.txt', 'w', encoding="utf-8") as f:
print(tweets, file=f)

那么它就不会打印,我得到一个错误信息:

future warning username is deprecated, use user.username instead

备注:在您使用open[在写模式下]打印后,mode='w'文件意味着文件将被每次打印覆盖,只有最后一次打印将显示。如果您想保留所有的tweets对象,您应该在中添加。循环[因为如果你在循环外打印,只会保存最后一个,因为tweets也会覆盖每个循环]:

# for i, tweet in...
# tweets = ....
with open('file.txt', 'a', encoding="utf-8") as f:
print(tweets, file=f)

这没有任何意义——这是一个警告消息,而不是一个错误消息,它不应该停止或中断你的程序;而且,这个警告不应该出现除非你的代码中有tweet.username之类的东西[如果你这样做,那么你可能应该用tweet.user.username作为警告指示]。

我无法重现错误,您如何打印应该与触发消息没有任何关系,但如果这真的是只有在消息出现和不出现的时间之间存在差异,那么您可以尝试其他方法将其保存到文件中,例如[在循环中]将所有tweet收集到列表中,然后[在循环之后]将该列表转换为多行字符串以写入文件:

import snscrape.modules.twitter as twitter
maxTweets = 10
keyword='salvation'
timeStr = 'since:2021-11-01 until:2023-01-01 lang:"en" '
twGen = twitter.TwitterSearchScraper(f'{keyword} {timeStr} ').get_items() 
allTweets = []
for i, tweet in enumerate(twGen):
if i > maxTweets: break
tweets = {
"tweet.url" : tweet.url
}   
allTweets.append(tweets)
## [OUTSIDE loop]
with open('file.txt', 'w', encoding="utf-8") as f:
f.write('n'.join[str(t) for t in allTweets])

最新更新