使用Twitter API获取推特数据

最近由于实验室研究需求,需要对Twitter15及Twitter16数据集进行扩展。具体为:1.根据user_id,获取用户画像;2.根据tweet_id,获取推文下的评论。

连接TwitterAPI

首先根据自己申请的推特开发者账号,去连接Twitter API

import tweepy
import time
import csv
import pandas as pd
import json
from collections import OrderedDict
import datetime
import re# 填写twitter提供的开发Key和secret
consumer_key = 'XXX'
consumer_secret = 'XXX'
access_token = 'XXX'
access_token_secret = 'XXX'# 提交你的Key和secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)# 获取类似于内容句柄的东西
api = tweepy.API(auth, proxy='127.0.0.1:7890')

读取tweet_id

# 获取所有的tweet_id
with open('uid.csv','r',encoding='utf-8') as f1:reader = csv.reader(f1)tweets_id = [row[0] for row in reader]print(tweets_id)print(len(tweets_id))
f1.close()

根据tweet_id爬取推文评论

for tweet_id in tweets_id:print(f"正在获取 tweet_id = %s 的推特的评论..." % tweet_id)with open('comments_id/' + tweet_id + '.csv', 'r', encoding='utf-8') as f2:reader = csv.reader(f2)comments_id = [row[0] for row in reader]with open('comments/' + tweet_id + '.csv', 'a', encoding='utf-8') as f3:for comment_id in comments_id:print(f"正在获取 comment_id = %s 的评论内容..." % comment_id)flag = 0while flag == 0:try:comment = api.get_status(id=comment_id).text# print(type(comment))except Exception as e:print(repr(e))if repr(e) == "TweepError([{'code': 179, 'message': 'Sorry, you are not authorized to see this status.'}])":print("没有权限查看此条评论!")flag = 1comment_list = [comment_id,]breakelif repr(e) == "TweepError([{'code': 144, 'message': 'No status found with that ID.'}])":print("此条评论已被删除!")flag = 1comment_list = [comment_id, ]breakelif repr(e) == "TweepError([{'code': 63, 'message': 'User has been suspended.'}])":print("用户被冻结!")flag = 1comment_list = [comment_id, ]breakelif repr(e) == "TweepError([{'code': 34, 'message': 'Sorry, that page does not exist.'}])":print("该页面不存在!")flag = 1comment_list = [comment_id, ]breakelse:print("网络不稳定,正常重新连接...")flag=0else:flag = 1print("成功找的此条评论!")print(comment)pattern1 = re.compile(r'\@(?:.|\s)*? ')comment = ''.join(re.sub(pattern1, '', comment))pattern2 = re.compile(r'\@(?:.|\s)*?$')comment = ''.join(re.sub(pattern2,'',comment))comment = ''.join(re.sub('@','',comment))pattern3 = re.compile(r'\n')comment = ''.join(re.sub(pattern3, ' ', comment))print(comment)comment_list = [comment_id, comment]breakwriter = csv.writer(f3)writer.writerows([comment_list])f3.close()f2.close()

读取所有的user_id

# 获取所有的user_id
with open('uid.csv','r',encoding='utf-8') as f1:reader = csv.reader(f1)user_ids = [row[1] for row in reader]print(user_ids)print(len(user_ids))

根据user_id爬取用户画像

# 获取所有的user_id
with open('uid.csv','r',encoding='utf-8') as f1:reader = csv.reader(f1)user_ids = [row[1] for row in reader]print(user_ids)print(len(user_ids))for user_id in user_ids:print(f"正在查找用户ID=%s的用户信息..." % user_id)flag = 0while flag == 0:try:User = api.get_user(user_id=user_id)except Exception as e:print(repr(e))if repr(e) == "TweepError: [{'code': 50, 'message': 'User not found.'}]":print('用户不存在!')with open('user_not_found.csv','a',encoding='utf-8') as f:writer = csv.writer(f)writer.writerows(user_id)f.close()flag = 1breakelif repr(e) == "TweepError: [{'code': 50, 'message': 'User not found.'}]":print('用户被冻结!')with open('user_has_been_suspended.csv','a',encoding='utf-8') as f:writer = csv.writer(f)writer.writerows(user_id)f.close()flag = 1breakelse:print("网络不稳定,正在尝试重新连接...")flag = 0else:flag = 1user_dict = {"user_id":user_id}user_dict["name"] = User.nameuser_dict["screen_name"] = User.screen_nameuser_dict["location"] = User.locationuser_dict["profile_location"] = User.profile_locationuser_dict["description"] = User.descriptionuser_dict["protected"] = User.protecteduser_dict["followers_count"] = User.followers_countuser_dict["friends_count"] = User.friends_countuser_dict["listed_count"] = User.listed_countuser_dict["created_at"] = str(User.created_at)user_dict["favourites_count"] = User.favourites_countuser_dict["utc_offset"] = User.utc_offsetuser_dict["time_zone"] = User.time_zoneuser_dict["geo_enabled"] = User.geo_enableduser_dict["verified"] = User.verifieduser_dict["statuses_count"] = User.statuses_countuser_dict["lang"] = User.languser_dict["contributors_enabled"] = User.contributors_enableduser_dict["is_translator"] = User.is_translatoruser_dict["is_translation_enabled"] = User.is_translation_enableduser_dict["profile_background_tile"] = User.profile_background_tileuser_dict["profile_use_background_image"] = User.profile_use_background_imageuser_dict["has_extended_profile"] = User.has_extended_profileuser_dict["default_profile"] = User.default_profileuser_dict["default_profile_image"] = User.default_profile_imageuser_dict["following"] = User.followinguser_dict["follow_request_sent"] = User.follow_request_sentuser_dict["notifications"] = User.notificationsuser_dict["translator_type"] = User.translator_typeprint(user_dict)json_str = json.dumps(user_dict, indent=4, ensure_ascii=False)with open(user_id + '.json', 'w',encoding='utf-8') as f2:f2.write(json_str)break# time.sleep(1)# f2.close()
f1.close()

Python连接Twitter API读取用户画像及推特评论相关推荐

  1. Python 使用 twitter API 获取twitter用户信息

    Python 使用 twitter API 获取twitter用户信息 1. 概述 twitter作为国外极其大众化的社交平台,具有大量的海外用户,平台流动数据量极大,是国外人群生活数据的重要来源之一 ...

  2. Python连接钉钉群机器人每天自动推送国外天气

    Python连接钉钉群机器人每天自动推送国外天气 一.天气获取 我使用的是openweather api,这个api的官方文档写的十分详细,链接:openweather 打开链接,界面如下: 目前只有 ...

  3. python抓取抖音用户画像,摩羯天蝎居然刷得最多?

    日刷抖音三百条,悠悠一笑乐逍遥,夜深忽醒窗外事,不知今夕是何年. 要从上个月说起,那天晚上准备睡觉了,然后朋友突然发来一个抖音热门视频. 一向一本正经苟于工作的我,竟然沉醉于小姐姐的甜蜜的笑容,加之想 ...

  4. 使用Hybris Commerce User API读取用户信息时,电话字段没有返回

    在使用Hybris Commerce User API读取一个user信息时,我遇到一个问题,在API返回的结构里没有包含期望看到的Phone字段. 仔细观察Swagger里对response结构的说 ...

  5. python连接linux服务器读取txt文件_python 读取Linux服务器上的文件方法

    使用Python语句,读取Linux远端服务器上的文件打印到控制台的代码实现: 下载包:paramiko import paramiko #服务器信息,主机名(IP地址).端口号.用户名及密码 hos ...

  6. Python利用Twitter API根据tweet id抓取tweet(via tweepy/twython)

    1.申请Twitter Developer账号 要抓取twitter平台信息的第一步是在Twitter Developer官方网站(https://developer.twitter.com/en)申 ...

  7. python连接mysql,并读取文件写入mysql

    PyMysql的使用 菜鸟教程:https://www.runoob.com/python3/python3-mysql.html(安装+介绍) # 导入pymysql模块 import pymysq ...

  8. python连接linux服务器读取txt文件_Python文件处理

    1.创建文件: f = file('myfile.txt','w')    #myfile 为文件名,w为写权限. f .write("hello world!")    #hel ...

  9. python用户画像_新闻个性化推荐系统源码之构建离线用户和文章特征

    我们完成了文章画像和用户画像的构建,画像数据主要是提供给召回阶段的各种召回算法使用.接下来,我们还要为排序阶段的各种排序模型做数据准备,通过特征工程将画像数据进一步加工为特征数据,以供排序模型直接使用 ...

最新文章

  1. 让 VAGRANT 启动并运行起来
  2. 我写了一个脚本,可在“任意”服务器上执行命令!
  3. 在电脑上实现手机app抓包
  4. 利用zookeeper实现发布订阅模式
  5. bool python 运算_python中的布尔操作
  6. vue 自学笔记(七) 组件细节问题
  7. Hbase shell练习题
  8. java分享第十六天( java读取properties文件的几种方法java配置文件持久化:static块的作用)...
  9. ExtJS视频教程 ExtJS入门到精通教程下载
  10. 【linux】Redhat 7 更新 yum源
  11. centos7安装并使用supervisor管理服务队列
  12. 【xsy1061】排列 树状数组
  13. 划片机是芯片切割制造流程中一个重要的环节
  14. Pilosa文档翻译(二)入门指南
  15. 一元二次方程求根计算机的代码,一元二次方程求根Java源程序代码.doc
  16. contiki学习笔记(九)文件系统CFS
  17. 计算机网络(4.1)——数据链路层的功能概述、封装成帧和透明传输
  18. 解决华为手机InputMethodManager和GestureBoostManager的内存泄露的问题
  19. go语言与区块链开发
  20. 实现Windows下Qt扫描U盘的两种方式

热门文章

  1. Redis命令详解:Pub/Sub
  2. 什么叫行业最佳实践?
  3. 【基于neo4j的音乐知识图谱及智能问答系统-哔哩哔哩】 https://b23.tv/pC3TmqY
  4. 简述云平台和相关软件工具
  5. 2021-01-27 SD8002A芯片分析回路中喇叭的工作电路路径
  6. Answering Visual-Relational Queries in Web-Extracted Knowledge Graphs
  7. matlab中如何从一个矩阵的行列中找出 0 元素的个数 或者位置 并作为判断条件
  8. C++ Linux下通过USB控制Nikon相机拍照和抓取照片
  9. Vue中Vnode的创建与处理
  10. spring-boot项目实例