本文主要内容来自 tweepy 官方文档,加入了一些必要的解释说明并剔除冗余的句子,便于国内用户参阅使用。

  纯手工码字,支持原创

tweepy官方文档:​​http://docs.tweepy.org/en/latest/getting_started.html​

what's the tweepy?

  tweepy 是专门用于在 Python 中处理 Twitter API 的模块。,使用方式相当简洁,省去了手动开发 Twitter 爬虫的成本。

  抓取 Twitter 数据的重点是 twitter 要求所有请求都必须经过 OAuth 认证,而 tweepy 这个包提供专门的 auth 功能,在这方面的设定让 authentication 变得十分方便。

注意:国内 Twitter 是被墙的,所以即使使用 tweepy 也必定要面对无法连接成功的状况。记得提前架好梯子。


安装

pip install tweepy



秘钥

  使用前需要现在 Twitter  官网上申请好秘钥,用于鉴权。

consumer_key = 'xxxxxxxxx'
consumer_secret = 'xxxxxxxxx'
access_token = 'xxxxxxxxx'
access_token_secret = 'xxxxxxxxx'



简单的例子

import tweepy

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

public_tweets = api.home_timeline()
for tweet in public_tweets:
print(tweet.text)



API

  API 类提供对整个 twitter restapi 方法的访问。每个方法都可以接受各种参数并返回响应。下文会着重介绍。

  tweepy 同时也支持长链接的形式得到即时信息。下文 stream 会介绍。


返回值

  tweepy API 的返回值一般都是对象,不同的对象取值字段不同,具体需要自己 debug

  • 推文相关——​Status 对象
  • 用户相关的——​User 对象
  • 好友相关的——​FriendShip 对象
  • 搜索记录相关的——​SavedSearch 对象


一、身份验证

  tweepy 提供两种鉴权方式:application-user 和  application-only,操作的是 tweepy.AuthHandler 类的对象

  • 鉴权1——application-user
  • # 1.绑定公钥
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    # 使用回调函数:auth = tweepy.OAuthHandler(consumer_key, consumer_secret, callback_url)

    # 2.绑定私钥
    # ---- 方式一:知道私钥,直接绑定
    auth.set_access_token(access_token, access_token_secret)
    # ---- 方式二:不知道私钥,先获取后绑定
    redirect_user(auth.get_authorization_url())
    auth.get_access_token("verifier_value")

    # 3.构造api
    api = tweepy.API(auth)


  • 鉴权2——application-only​:这种方式不需要绑定私钥,用于只需要读权限的操作
  • auth = tweepy.AppAuthHandler(consumer_key, consumer_secret)
    api = tweepy.API(auth)
    # 搜索关键词tweepy
    for tweet in tweepy.Cursor(api.search, q='tweepy').items(10):
    print(tweet.text)


二、分页

  有时候 Twitter 的数据量相当的庞大,所以会需要经常使用分页。比如遍历时间线、用户列表、直接消息等操作。

  tweepy 为我们提供了很便捷的分页功能。

示例:迭代经过身份验证的用户(即当前秘钥对应的用户)时间线中的状态

# 操作所有时间线
for status in tweepy.Cursor(api.user_timeline).items():
# process status here
process_status(status)

# 操作每一页
for page in tweepy.Cursor(api.user_timeline).pages():
# page is a list of statuses
process_page(page)

# 操作前200条
for status in tweepy.Cursor(api.user_timeline).items(200):
process_status(status)

# 操作前3页
for page in tweepy.Cursor(api.user_timeline).pages(3):
process_page(page)



三、粉丝

  tweepy 可以获得指定用户的粉丝数、粉丝们,并进行粉的操作

# 获取我的粉丝
fs = tweepy.Cursor(api.followers)
for follower in fs.items():
follower.follow() # 粉



  粉丝数量很多的情况下可以使用生成器

# 函数封装了生成器下一页功能,但是如果已处于最后一页却还执行下一页会报错,这里加了容错处理
def limit_handled(cursor):
while True:
try:
yield cursor.next() # 生成器下一页功能
except tweepy.RateLimitError:
time.sleep(15 * 60)

# 输出好友数量小于300的用户昵称
for follower in limit_handled(tweepy.Cursor(api.followers).items()):
if follower.friends_count < 300:
print(follower.screen_name)



四、流媒体 stream

  tweepy 提供类似于 websocket 的长链接功能,称之为 stream。客户端在通过身份验证和基本的连接之后可以被动实时的获得数据,比如:关注特朗普的推特,当特朗普发推时我们的程序就能收到;或者监听指定关键词比如新冠肺炎,只要有包含关键词的推文我们就能收到。

  stream 和 Rest api 不同,前者是长链接被动获取实时获取数据,后者则是主动请求以获得数据。

  tweepy 实现了 ​StreamListener​ 类,我们想要实现 stream 的功能只要继承这个类并重写它的 ​on_status​ 方法即可,on_status 方法会在得到数据时被调用

import tweepy

# 继承 StreamListener
class MyStreamListener(tweepy.StreamListener):
#重写 on_status
def on_status(self, status):
print(status.text)
# status 是一个对象,里面包含了该条推文的所有字段,比如推文内容、点赞数、评论数、作者id、作者昵称、作者粉丝数等等

# 当流媒体出错时被调用,如:身份验证失败、网络错误等等
def on_error(self, status_code):
if status_code == 420:
return False #returning False in on_error disconnects the stream

# 实例化
myStreamListener = MyStreamListener()
# 身份验证,绑定监听流媒体
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener)
# --- 监听关键词Python相关的推文
myStream.filter(track=['python'])
# --- 关注某推特用户,只能通过ID
myStream.filter(follow=["2211149702"])
# --- 支持异步,参数is_async,推荐使用异步形式
myStream.filter(track=['python'], is_async=True)

# 关闭流媒体的监听
myStream.disconnect()


注:更多信息需要自行查看源码,源码并不是很难读


五、REST API

  tweepy 提供了一系列 API,基本全面支持 Twitter 网站的功能


5.1 时间线相关

API

说明

参数

返回值

API.home_timeline([since_id][, max_id][, count][, page])

返回身份验证用户及其朋友发布的20个最新状态,包括转发。这相当于Web上的/timeline/home


  • since_id– 指定起始ID
  • max_id– 指定最大ID,只返回比该ID小的
  • count– 指定检索的数量
  • page– 指定页码,注意页数限制


list,元素是status对象

API.statuses_lookup(id_[, include_entities][, trim_user][, map_]

[, include_ext_alt_text][, include_card_uri])


返回指定推特的详情,最多一百条,由id_参数指定


  • id_– 存放推特id的列表,最多100个id
  • include_entities–默认为True,当设置为False时返回值中不包含entities
  • trim_user–默认为False,用于指定返回值中是否包含推文用户的信息
  • map_– 是否包含无法显示的推文,默认是False
  • include_ext_alt_text– If alt text has been added to any attached media entities, this parameter will return an ext_alt_text value in the top-level key for the media entity.
  • include_card_uri– 是否包含card_uri


list,元素是status对象

API.user_timeline([id/user_id/screen_name][, since_id][, max_id][, count][, page])

返回身份验证用户或指定用户发布的20个最新状态。也可以通过id参数获取指定用户的时间线


  • id– 指定用户的id或昵称
  • user_id– 指定用户的ID,当有效的用户ID也是有效的昵称时,有助于消除歧义
  • screen_name– 指定用户的昵称
  • since_id– 指定起始ID
  • max_id– 指定最大ID,只返回比该ID小的
  • count– 指定检索的数量
  • page– 指定页码,注意页数限制


list,元素是status对象

API.retweets_of_me([since_id][, max_id][, count][, page])

返回已验证用户最近转发的20条推文


  • since_id– 指定起始ID
  • max_id– 指定最大ID,只返回比该ID小的
  • count– 指定检索的数量
  • page– 指定页码,注意页数限制


list,元素是status对象

API.mentions_timeline([since_id][, max_id][, count])

返回最近20次提及,包括转发


  • since_id– 指定起始ID
  • max_id– 指定最大ID,只返回比该ID小的
  • count– 指定检索的数量


list,元素是status对象


5.2 Status 相关(推文)

API

说明

参数

返回值

API.get_status(id[, trim_user]

[, include_my_retweet]

[, include_entities]

[, include_ext_alt_text]

[, include_card_uri])


返回由指定ID的推文详情


  • id– 指定推文ID.
  • trim_user– 默认为False,用于指定返回值中是否包含推文用户的信息
  • include_my_retweet– 布尔值,是否包含转发字段
  • include_entities– 默认为True,当设置为False时返回值中不包含entities
  • include_ext_alt_text– If alt text has been added to any attached media entities, this parameter will return an ext_alt_text value in the top-level key for the media entity.
  • include_card_uri– 是否包含card_uri


status对象

API.update_status(status[, in_reply_to_status_id]

[, auto_populate_reply_metadata]

[, exclude_reply_user_ids]

[, attachment_url]

[, media_ids]

[, possibly_sensitive]

[, lat][, long][, place_id]

[, display_coordinates]

[, trim_user][, enable_dmcommands]

[, fail_dmcommands][, card_uri])


发表推文,注意不可重复发相同推文,否则返回403;不可一次性发布超过限制数量的推文,否则返回403


  • status– 推文内容
  • in_reply_to_status_id– 本条推文回复的作者ID。注意:,除非状态文本中提到此参数引用的Tweet的作者,否则此参数将被忽略。因此,必须在推文中包含@username,其中username是引用Tweet的作者。.
  • auto_populate_reply_metadata– 如果设置为True并与in-reply-to-u status-id一起使用,则会从原始Tweet中查找@提到的,并从那里添加到新Tweet。随着回复链的增长,这个将把@references附加到扩展Tweet的元数据中,直到达到@references的限制。如果原始推文被删除,回复将失败。
  • exclude_reply_user_ids– 当与auto_populate_reply_metadata一起使用时,将从服务器生成的扩展Tweet上的@references前缀中删除的以逗号分隔的用户id列表。请注意,不能删除前导的@notice,因为它会破坏in reply to status id语义。尝试删除它将被忽略。
  • attachment_url– 附件URL,为了使url不计入扩展Tweet的状态正文中,请提供一个url作为Tweet附件。此URL必须是Tweet永久链接或直接消息深度链接。任意的非Twitter url必须保留在状态文本中。传递给attachment_url参数的url与Tweet permalink或Direct Message deep link不匹配,将在创建Tweet时失败并导致异常。
  • media_ids– 要与推特关联的媒体ID列表。在Tweet中最多可以包含4张照片、1张动画GIF或1个视频。
  • possibly_sensitive– 如果你上传的Tweet媒体可能被认为是敏感内容,例如裸体或医疗程序,必须将此值设置为true。
  • lat– 此Tweet所指位置的纬度。需要在-90.0到+90.0(北为正)范围内。如果没有相应的long参数,将忽略它。
  • long– 此Tweet所指位置的经度。经度的有效范围是-180.0到+180.0(东为正)。如果超出该范围,如果不是数字,如果启用了地理坐标,或者没有相应的lat参数,则将忽略此参数。
  • place_id– 世界上的一个地名.
  • display_coordinates– 是否在发送Tweet的确切坐标上加一个pin
  • trim_user– 默认为False,用于指定返回值中是否包含推文用户的信息
  • enable_dmcommands– 当设置为true时,启用用于将直接消息作为状态文本的一部分发送给用户的快捷方式命令。如果设置为false,则禁用此行为,并在发布的状态文本中包含任何前导字符
  • fail_dmcommands–设置为true时,将导致以shortcode命令开头的任何状态文本返回一个API错误。当设置为false时,允许在状态文本中发送shortcode命令并由API执行。
  • card_uri– Associate an ads card with the Tweet using the card_uri value from any ads card response.


status对象

API.update_with_media(filename[, status]

[, in_reply_to_status_id]

[, auto_populate_reply_metadata]

[, lat][, long][, source][, place_id][, file])



目前已不废,推荐使用API.media_upload()。

更新已验证用户的状态。重复或太长的状态将被忽略。



  • filename– 要上传的图像的文件名。这将自动打开,除非指定了文件状态–状态更新的文本。
  • status– 文件内容.
  • in_reply_to_status_id– 答复的推文的id
  • auto_populate_reply_metadata– Whether to automatically include the @mentions in the status metadata.
  • lat– 维度
  • long– 经度
  • source– 这个只支持加州,所以咱忽略不用
  • place_id– 地名ID
  • file– 一个文件对象



API.destroy_status(id)

删除自己的一条推文

id - 推文id

status对象

API.retweet(id)

转发

id - 要转发的推文id

status对象

API.retweeters(id[, cursor][, stringify_ids])

得到转发了该条推文的用户id列表最多返回100条


  • id– 指定推文id
  • cursor– 传-1则分页,否则得到指定页的数据
  • stringify_ids– 是否将id作为字符串返回


list,元素是status对象

API.retweets(id[, count])

返回指定推特的前count次转发,最多100


  • id– 指定推文id
  • count– 数量,小于等于100


list,元素是status对象

API.unretweet(id)

取消转发


id – 指定推文id


status对象


5.3 User 相关(用户)

API

说明

参数

返回值

API.get_user(id/user_id/screen_name)

返回指定用户信息


  • id– 指定用户ID或昵称
  • user_id– 指定用户ID
  • screen_name– 指定用户昵称


user对象

API.me()

返回认证用户信息

user对象

API.friends([id/user_id/screen_name][, cursor]

[, skip_status][, include_user_entities])



返回指定用户的前count个好友,最多100,

如果没有指定用户则为当前用户



  • id– 指定用户ID或昵称
  • user_id– 指定用户ID
  • screen_name– 指定用户昵称
  • cursor– 将结果进行分页
  • count– 当前页数量
  • skip_status– 默认为False,返回值中是否包含status字段
  • include_user_entities– 默认是True,返回值中是否包含entities字段


list,元素是user对象

API.followers([id/screen_name/user_id][, cursor])

返回指定用户的follower,最多100,

如果没有指定用户则为当前用户



  • id– 指定用户ID或昵称
  • user_id– 指定用户ID
  • screen_name– 指定用户昵称
  • cursor– 将结果进行分页
  • count– 当前页数量
  • skip_status– 默认为False,返回值中是否包含status字段
  • include_user_entities– 默认是True,返回值中是否包含entities字段



list,元素是user对象

 API.lookup_users([user_ids][, screen_names][, include_entities][, tweet_mode])


 返回fully-hydrated用户,最多100

  • 只能跟踪受保护的用户才能看到他们最近的状态更新。如果不跟踪受保护的用户,则其状态将被删除。
  • 用户ID或昵称的顺序可能与返回数组中的用户顺序不匹配。
  • 如果请求的用户未知、已挂起或已删除,则不会在结果列表中返回该用户。
  • 如果返回一个用户对象不能满足任何查找条件,则会抛出一个404。



  • ser_ids– 用户ID列表,最多100个
  • screen_names– 用户昵称列表,最多100个
  • include_entities– 默认是True,返回值中是否包含entities字段
  • tweet_mode– 参数值是compat或extended,
  • compat:包含140个字符的tweet提供兼容模式
  • extended:包含140个字符的tweet提供扩展模式。


list,元素是user对象

 API.search_users(q[, count][, page])


运行类似于“查找人员”按钮搜索Twitter.com网站;

效果等同于网站上进行用户搜索。

只能从这个API检索前1000个匹配项。



  • q– The query to run against people search.
  • count– 数量,不能大于20
  • page– 页码,注意页数限制


list,元素是user对象


5.4 Direct Message 相关

 API

说明 

 参数

返回值 

 API.get_direct_message([id][, full_text])

返回指定的 direct message


  • id– 指定 direct message 的ID
  • full_text–默认为False,是否返回全文信息,False情况下只返回140个字节


DirectMessage对象

 API.list_direct_messages([count][, cursor])


返回30天内接受和发送的所有 direct message

默认按时间倒序



  • count– 当前页数量
  • cursor– 分页


list,元素是DirectMessage对象

 API.send_direct_message(recipient_idtext

[, quick_reply_type][, attachment_type]

[, attachment_media_id])


 向指定用户发送一条 direct message


  • recipient_id– 接收者ID
  • text– 内容,最多10,000 字符.
  • quick_reply_type– 快速答复的类型,参数值为以下三种
  • options:Array of Options objects (20 max).
  • text_input:Text Input object.
  • location:Location object.
  • attachment_type– 附件类型, media 或 location.
  • attachment_media_id– 与附件关联的media的ID,一条 direct message只有一个


DirectMessage对象

 API.destroy_direct_message(id)

删除当前用户的一条 direct message

 id – 指定 direct message 的ID

None


5.5 Friendship 相关

API

说明

参数

返回值

API.create_friendship(id/screen_name/user_id[, follow])

与指定用户建立好友关系(也可以是关注指定好友)


  • id– 指定用户ID或昵称
  • screen_name– 指定用户昵称
  • user_id– 指定用户ID
  • follow– 不仅成为好友,而且还关注他


user对象

API.destroy_friendship(id/screen_name/user_id)

删除指定用户的好友关系(也可以是取消关注)


  • id– 指定用户ID或昵称
  • screen_name– 指定用户昵称
  • user_id– 指定用户ID


user对象

API.show_friendship(source_id/source_screen_nametarget_id/target_screen_name)

返回两个指定用户的好友关系


  • source_id– 源用户ID
  • source_screen_name– 源用户昵称
  • target_id– 目标用户ID
  • target_screen_name– 目标用户昵称


FriendShip对象

API.friends_ids(id/screen_name/user_id[, cursor])

返回关注指定用户的用户ID列表(就是粉丝)


  • id– 指定用户ID或昵称
  • screen_name– 指定用户昵称
  • user_id– 指定用户ID
  • cursor– 分页


list,元素是ID

API.followers_ids(id/screen_name/user_id)

返回指定用户的关注用户ID列表


  • id– 指定用户ID或昵称
  • screen_name– 指定用户昵称
  • user_id– 指定用户ID
  • cursor– 分页


list,元素是ID


5.6 Account 相关(即当前用户)

API

说明

参数

返回值

API.verify_credentials([include_entities][, skip_status][, include_email])

验证用户是否有效


  • include_entities– 默认为True,当设置为False时返回值中不包含entities
  • skip_status– 默认为False,返回值中是否包含status字段
  • include_email– 是否包含email字段


user对象或False

API.rate_limit_status()

返回当前用户的指定API的速率限制

resources – 列表,元素为API。

JSON

API.update_profile_image(filename)

更新头像,必须是GIF、JPG或PNG

filename – 本地文件的路径,不能是远程的URL

user对象 

API.update_profile_background_image(filename)

更新背景图,必须是GIF、JPG或PNG

filename – 本地文件的路径,不能是远程的URL

user对象 

API.update_profile([name][, url][, location][, description])

设置用户选项,只能设置在网站设置页的“帐户”选项卡下的选项。


  • name– 20个字符
  • url– 100个字符,必须是 “​​http://​​” 开头
  • location– 30个字符
  • description– 160个字符


user对象


5.7 Favorite 相关(喜欢的推文)

API

说明

参数

返回值

API.favorites([id][, page])

返回指定用户喜欢的推文列表,默认为当前用户


  • id– 用户ID或昵称
  • page– 页码,注意页数限制


list,元素是status对象

API.create_favorite(id)

喜欢指定推文


id – 推文ID


status对象

API.destroy_favorite(id)

取消喜欢指定推文

id – 推文ID

status对象



5.8 Block 相关(黑名单)

API

说明

参数

返回值

API.create_block(id/screen_name/user_id)

阻止指定用户,解除当前用户与指定用户的好友关系(黑名单功能)


  • id– 指定用户ID或昵称
  • screen_name– 指定用户昵称
  • user_id– 指定用户ID


user对象

API.destroy_block(id/screen_name/user_id)

取消拉黑


  • id– 指定用户ID或昵称
  • screen_name– 指定用户昵称
  • user_id– 指定用户ID


user对象

API.blocks([page])

返回黑名单列表

page – 也爱,注意页数限制

list,元素是user对象

API.blocks_ids([cursor])

返回黑名单ID列表

cursor – 分页

list,元素是黑名单user的ID


5.9 Mute 相关(屏蔽)

API

说明

参数

返回值

API.create_mute(id/screen_name/user_id)

屏蔽指定用户


  • id– 指定用户ID或昵称
  • screen_name– 指定用户昵称
  • user_id– 指定用户ID


user对象

API.destroy_mute(id/screen_name/user_id)

取消屏蔽


  • id– 指定用户ID或昵称
  • screen_name– 指定用户昵称
  • user_id– 指定用户ID


user对象

API.mutes([cursor][, include_entities][, skip_status])

返回屏蔽列表


  • cursor– 页码
  • include_entities– 默认为True,当设置为False时返回值中不包含entities
  • skip_status– 默认为False,返回值中是否包含status字段


list,元素是user对象

API.mutes_ids([cursor])

返回屏蔽ID列表

cursor – 分页

list,元素是屏蔽user的ID


5.10 Spam Reporting 相关(垃圾信息)

API

说明

参数

返回值

API.report_spam(id/screen_name/user_id[, perform_block])

拉黑指定用户,并发送垃圾报告


  • id– 指定用户ID或昵称
  • screen_name– 指定用户昵称
  • user_id– 指定用户ID
  • perform_block– 默认为True,是佛偶举报该用户为垃圾邮件用户


user对象


5.11 Saved Searches 相关(保存的搜索,类似于收藏)

API

说明

参数

返回值

API.saved_searches()

返回当前用户保存的搜索记录

list,元素是SavedSearch对象

API.get_saved_search(id)

返回当前用户保存的指定搜索记录

id – 搜索记录的ID

SavedSearch对象

API.create_saved_search(query)

增加一条搜索记录

query – 搜索的 query 

SavedSearch对象

API.destroy_saved_search(id)

删除一条保存的搜索记录,只能删自己的

id – 搜索记录的ID

SavedSearch对象


5.12 其他

  剩下的几个相关的 API 个人觉得基本不会使用,详情请自行参阅官网


ERROR 异常

  tweepy 提供了几个异常类,便于我们捕捉异常​

tweepy.TweepError

  涵盖了几乎所有 tweepy 的异常


tweepy.RateLimitError

  当 API 访问量超出限制时会触发该异常,该异常也可以被 tweepy.TweepError 捕捉到