用fiddler捕获请求Twitter的返回数据,并将其复制粘贴存入txt文件。数据结构大致如下:
安装XlsxWriter包
#使用pip下载并安装包(本机已安装过)
C:\Users\limj3>pip install Xlsxwriter
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Requirement already satisfied: Xlsxwriter in d:\anaconda2\lib\site-packages (1.1.5)
#检查是否安装成功
C:\Users\limj3>python
Python 2.7.16 |Anaconda, Inc.| (default, Mar 14 2019, 15:42:17) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>import xlsxwriter
>>>
#!/usr/bin/python
# coding=utf-8
import json
import sys
import xlsxwriter
#获取txt文件
f = open("twitter.txt","r")
txt = f.read()
# 使用json.loads方法将json解码为python对象
json_repose = json.loads(txt)
globalObjects = json_repose['globalObjects']
tweets = globalObjects["tweets"] #已得到放有目标内容的最底层json
f.close() #关闭文件
# 使用xlsxwriter
# 创建表格
workbook = xlsxwriter.Workbook('D:\PyCharm\test\Twitter.xlsx') #创建或指定excel文件
worksheet1 = workbook.add_worksheet() #创建工作表
worksheet1.activate() #激活工作表
title = [U'时间',U'用户id',U'内容'] #表格title
worksheet1.write_row('A1',title) #title 写入Excel
#循环写入行内容,一行内容即为data[]
i=2
for key in tweets:
data = [tweets[key]["created_at"],tweets[key]["id"],tweets[key]["full_text"]]
row = 'A'+str(i)
worksheet1.write_row(row, data)
i += 1
workbook.close() #关闭工作表
注:xlsxwriter的写入是会覆盖原来在表中的数据的。暂时我还没发现增量写入的方法,希望朋友们指教
xlsxwriter还有很多对excel的操作可以实现,比如图表,统计,样式,甚至权限管理等等。官方技术文档:https://xlsxwriter.readthedocs.io/